我有一个数组,例如$ arr = array(1,3,2,8,5,7,4,6,0);
如何使用冒泡排序方法进行自定义排序?
谢谢
答案 0 :(得分:1)
你去:
$a=array(5,4,3,1,2);
for($j=0; $j < count($a)-1; $j++) {
$swapped=false;
$i=0;
while ($i < count($a)-1) {
if( $a[$i] > $a[$i+1]) {
$c=$a[$i];
$a[$i]=$a[$i+1];
$a[$i+1]=$c;
$swapped=true;
}
++$i;
}
if( !$swapped )
break;
}
print_r($a);
输出:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
答案 1 :(得分:-4)
$arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
$sortedArr = bubbleSort($arr);
var_dump($sortedArr);
function bubbleSort(array $arr) {
$sorted = false;
while (false === $sorted) {
$sorted = true;
for ($i = 0; $i < count($arr)-1; ++$i) {
$current = $arr[$i];
$next = $arr[$i+1];
if ($next < $current) {
$arr[$i] = $next;
$arr[$i+1] = $current;
$sorted = false;
}
}
}
return $arr;
}
echo "<pre>";
print_r(bubbleSort($arr));
http://blog.richardknop.com/2012/06/bubble-sort-algorithm-php-implementation/