Bubblrsort in PHP


May 27, 2012    Janaki Mahapatra, PHP

The follwoing function has two arguments one is array and other is 0 for ascending sort and 1 is for descending sort. <?php function BubbleSort($sort_array,$reverse) { for ($i = 0; $i < sizeof($sort_array); $i++) { for ($j = $i + 1; $j < sizeof($sort_array); $j++){ if($reverse) { if ($sort_array[$i] < $sort_array[$j]){ $tmp = $sort_array[$i]; $sort_array[$i] = $sort_array[$j]; $sort_array[$j] = $tmp; } } else{ if ($sort_array[$i] > $sort_array[$j]) { $tmp = $sort_array[$i]; $sort_array[$i] = $sort_array[$j]; $sort_array[$j] = $tmp; } } } } return $sort_array; } //Use like this : $array = array(10,65,32,100,41,1,99); $sorted = BubbleSort($array,0); echo"<pre>"; print_r($sorted); echo "</pre>"; ?>