<?php
$unsorted = array();
for ($i = 0; $i < 10; $i++) {
$unsorted[] = rand(0,1000);
}
print "Unsorted Array. <br />";
print implode(',', $unsorted);
print "<br />";
print "Sorted Array. <br />";
$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 排序冒泡算法 经典面试题
最新推荐文章于 2023-06-11 13:14:37 发布