PHP 排序冒泡算法 经典面试题



$unsorted = array();

for ($i = 0; $i < 10; $i++) {
$unsorted[] = rand(0,1000);
}

print "Unsorted Array.
";
print implode(',', $unsorted);

print "
";

print "Sorted Array.
";
$sort = bubble_sort($unsorted);
print implode(',',$sort);

function bubble_sort ($arr = array()) {
$size = false;
if ($arr and is_array($arr)) {
$size = count($arr);
for ($i = 0; $i < $size; $i++) {
for ($j = 0; $j < $size - $i - 1; $j++) {
if ($arr[$j+1] < $arr[$j]) {
// switch two elements
list($arr[$j], $arr[$j+1]) = array($arr[$j+1], $arr[$j]);
// $temp = $arr[$j+1];
// $arr[$j+1] = $arr[$j];
// $arr[$j] = $temp;
}
}
}
}
return $arr;
}

你可能感兴趣的:(php,sort)