Bubble Sort Algorithm

From Wiki, I found that the classic algorithm wiki is written in great detail.

Bubble sort (English: Bubble Sort) is a simple sorting algorithm.

It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted.

The name of this algorithm comes from the fact that smaller elements will slowly “float” to the top of the array through exchange.

Although this algorithm is one of the simplest sorting algorithms to understand and implement, it is very inefficient for sorting sequences beyond a few elements.

It is very helpful for getting started with algorithm understanding!

Here is how to write PHP:

<?PHP
function swap(&$x, &$y) {
$t = $x;
$x = $y;
$y = $t;
}
function bubble_sort(&$arr) {
for ($i = 0; $i < count($arr) - 1; $i++){
for ($j = 0; $j < count($arr) - 1 - $i; $j++){
if ($arr[$j] > $arr[$j + 1])
swap($arr[$j], $arr[$j + 1]);
}
}
}
$arr = array(5,2,7,3,4,1,6,8,0);
bubble_sort($arr);
print_r($arr);