Data Structure in PHP: Bubble Sort

Here is the code for a data structure items in PHP. It is about Bubble Sort. Bubble sort is the way of sorting data. This is regarded as bad algorithm due to its worst case performance O(n2). Average case performance is also same as O(n2). But this sorting algorithm is the first one generally thought in syllabus due to its easy to understand algorithm for human.

Here is the PHP code for bubble sort that uses nested loop method that reduce iteration count. For more on this I refer to Wiki.


<?php
// Bubble sort. Optimized nested loop method. http://en.wikipedia.org/wiki/Bubble_sort
function bubble_sort($arr) {
    $n = count($arr);
    for($i=1; $i < $n; $i++) {
      for ($j = $n-1; $j>=$i; $j--) {
        if ($arr[$j] < $arr[$j-1]) {
            list ($arr[$j-1], $arr[$j]) = array($arr[$j], $arr[$j-1]); // Swap
        }
      }
    }
    return $arr;
}
$arr = array(1,3,2,8,5,7,4,0);
echo '<pre>';
print("Before sorting");
print_r($arr);
$arr = bubble_sort($arr);
print("After sorting by using Bubble  sort");
print_r($arr);
?>
Comments are open for an year period. Please, write here on Facebook page.