php — 冒泡排序

$start = explode(' ', microtime());
$a = range(1, 1000);
shuffle($a);
$len = count($a);
//每个都跟它后面的比较
//for ($i = 0; $i < $len - 1; $i++) {
// for ($j = $i + 1; $j < $len; $j++) {
// if ($a[$i] > $a[$j]) {
// $temp = $a[$j];
// $a[$j] = $a[$i];
// $a[$i] = $temp;
// }
// }
//}
//两两比较
//for ($i = 0; $i < $len; $i++) {
// for ($j = $len - 1; $j > $i; $j--) {
// if ($a[$j] < $a[$j - 1]) {
// $temp = $a[$j - 1];
// $a[$j - 1] = $a[$j];
// $a[$j] = $temp;
// }
// }
//}
//如果是后面都是有序的后面就不用再比较排序了[1,3,2,4,5,6,7,8,9]
$flag = true;
for ($i = 0; $i < $len && $flag; $i++) {
    $flag = false;
    for ($j = $len - 1; $j > $i; $j--) {
        if ($a[$j] < $a[$j - 1]) {
            $flag = true;
            $temp = $a[$j - 1];
            $a[$j - 1] = $a[$j];
            $a[$j] = $temp;
        }
    }
}
// print_r($a);
$end = explode(' ', microtime());//用时
echo $end[0] + $end[1] - $start[0] - $start[1];