Skip to content

Instantly share code, notes, and snippets.

@KerryJones
Last active January 1, 2016 04:15
Show Gist options
  • Save KerryJones/9c069c693a3000cd3d62 to your computer and use it in GitHub Desktop.
Save KerryJones/9c069c693a3000cd3d62 to your computer and use it in GitHub Desktop.
PHP Bubble Sort O(n^2)
<?php
function bubbleSort(array $array) {
if ( empty( $array ) )
return $array;
$length = count($array);
for ( $i = 0; $i < $length - 1; $i++ ) {
$swapped = false;
for ( $j = 0; $j < $length - $i - 1; $j++ ) {
if ( $array[$j] > $array[$j + 1] ) {
$temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j + 1] = $temp;
$swapped = true;
}
}
if ( !$swapped )
break;
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment