Sergey Sergey - 4 months ago 12
PHP Question

PHP array sort using Bubble approach

I have a array such as $arr = array(1,3,2,8,5,7,4,6,0);

How can i use bubble sorting method for custom sort ?

Thank you

Answer
function  {
    $size = count($arr);
    for ($i=0; $i<$size; $i++) {
        for ($j=0; $j<$size-1-$i; $j++) {
            if ($arr[$j+1] < $arr[$j]) {
                swap($arr, $j, $j+1);
            }
        }
    }
    return $arr;
}

function swap(&$arr, $a, $b)
{
    $arr[$a] = $arr[$a] + $arr[$b] - ($arr[$b] = $arr[$a]);
}
$arr = array(1,3,2,8,5,7,4,6,0);
print_r(bubble_sort($arr));
Comments