Bubble sort algorithm is a basic algorithm for sorting sets of numbers. It is the one you will probably be confronted with at college. There are probably better sorting algorithms but since this is the one you will most likely encounter, I have decided to write a simple implementation of it in PHP.

The idea is simple. You iterate over an array (from the first to the last but one number) using a while loop until it’s sorted. In every iteration you compare the current and the next number. If the current number is greater than the next number, switch them. That’s in a case you want to sort the array in ascending order. For descending order it is very similar. Just change < to >.

Source Code:
<?php
    // Ascending order function
    function bubbleSortAsc(array $arr)
    {
        $sorted = FALSE;
        while ($sorted === FALSE)
        {
            $sorted = TRUE;
            for ($i = 0; $i < count($arr)-1; ++$i)
            {
                $current = $arr[$i];
                $next = $arr[$i+1];
                if ($next < $current)
                {
                    $arr[$i] = $next;
                    $arr[$i+1] = $current;
                    $sorted = FALSE;
                }
            }
        }
        return $arr;
    }
   
    // Descending order function
    function bubbleSortDesc(array $arr)
    {
        $sorted = FALSE;
        while ($sorted === FALSE)
        {
            $sorted = TRUE;
            for ($i = 0; $i < count($arr)-1; ++$i)
            {
                $current = $arr[$i];
                $next = $arr[$i+1];
                if ($next > $current)
                {
                    $arr[$i] = $next;
                    $arr[$i+1] = $current;
                    $sorted = FALSE;
                }
            }
        }
        return $arr;
    }
   
   
    // Call any function
    $arr_val = array(50, 1, 45, 10, 40, 20, 35, 30, 3, 2);
    $sortedArr = bubbleSortAsc($arr_val);
    print_r($sortedArr);
?>

Loading
Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Flying Twitter Bird Widget By ICT Sparkle