## 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) {
=>
int(0)
=>
int(1)
=>
int(2)
=>
int(3)
=>
int(4)
=>
int(5)
=>
int(6)
=>
int(7)
=>
int(8)
=>
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) {
=>
int(9)
=>
int(8)
=>
int(7)
=>
int(6)
=>
int(5)
=>
int(4)
=>
int(3)
=>
int(2)
=>
int(1)
=>
int(0)
}
```
0.00 avg. rating (0% score) - 0 votes