PHP Bubble Sort Algorithm

Wiki
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 >.

Ascending order

<?php

$arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
$sortedArr = bubbleSort($arr);
var_dump($sortedArr);

function bubbleSort(array $arr) {
    $sorted = false;
    while (false === $sorted) {
        $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;
}

Will result in

array(10) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
  [8]=>
  int(8)
  [9]=>
  int(9)
}

Descending order

<?php

$arr       = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
$sortedArr = bubbleSortDesc($arr);
var_dump($sortedArr);

function bubbleSortDesc(array $arr) {
    $sorted = false;
    while (false === $sorted) {
        $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;
}

Will result in

array(10) {
  [0]=>
  int(9)
  [1]=>
  int(8)
  [2]=>
  int(7)
  [3]=>
  int(6)
  [4]=>
  int(5)
  [5]=>
  int(4)
  [6]=>
  int(3)
  [7]=>
  int(2)
  [8]=>
  int(1)
  [9]=>
  int(0)
}
0.00 avg. rating (0% score) - 0 votes