Home > Sort algorithms > Bubble Sort algorithm – PHP implementation

Bubble Sort algorithm – PHP implementation

Algorithm:

  1. Compare each pair of adiacent elements from the beginning of an array and, if they are in reversed order, swap them.
  2. If at least one swap has be done repeat step 1.

Is one of the most inefficient algorithm.
Performance:

  • Worst case: O(n2)
  • Average case: O(n2)
  • Best case: O(n)

PHP implementation:

    /**Function for sorting an array with bubble sort algorithm.
     * 
     * @param array $array
     * @return array
     */
    public static function bubbleSort(array $array) {
        $swapped=true;
        $j=0;
        $length=count($array);
        while($swapped) {
            $swapped=false;
            $j++;
            $comp=$length-$j;
            for ($i=0;$i<$comp;$i++) {
                if ($array[$i]>$array[$i+1]) {
                    $tmp=$array[$i];
                    $array[$i]=$array[$i+1];
                    $array[$i+1]=$tmp;
                    $swapped=true;
                }
            }
        }
        return $array;
    }

Bibliography:

  1. Introduction to Algorithms – Thomas H.Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein
  2. Algorithms – Robert Sedgewick
  3. http://en.wikipedia.org/wiki/Bubble_sort
Advertisements
Categories: Sort algorithms Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: