PHP Algorithm - Bubble Sort

function bubble_sort($arr)
{
    $count = count($arr);
    if ($count <= 1) {
        return $arr;
    }
    $times = $count - 1;
    for ($i = 0; $i < $times; $i ++) {
        for ($j = 0; $j < $count - $i - 1; $j ++) { // The last one in the first pass is already the maximum value, so $count-$i
            if ($arr[$j] > $arr[$j + 1]) {
                $tmp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $tmp;
            }
        }
    }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326993528&siteId=291194637