Introduction
There are many ways to sort an array in PHP the
easiest being to use the sort() function built into PHP. This sort function is
quick but has it's limitations, especially when sorting things like dates as PHP
usually guesses which value is higher than the other and can produce odd
results. However, there are plenty of sorting algorithms available than can
allow you to sort an array in any way you want. The
bubble sort is a simple sorting
algorithm. It works by repeatedly stepping through the list to be sorted,
comparing each pair of adjacent items and swapping them if they are in the wrong
order. The pass through the list is repeated until no swaps are needed, which
indicates that the list is sorted. The algorithm gets its name from the way
smaller elements “bubble” to the top of the list.
The simplest of these is called the bubble sort. Here is a function that will
sort an array of values using the bubble sort algorithm
Example : The simple example of bubble
sort in php
function
bubbleSort ($items)
{
$size
= count($items);
for ($i=0;
$i<$size; $i++)
{
for ($j=0;
$j<$size-1-$i;
$j++) {
if ($items[$j+1]
< $items[$j]) {
arraySwap($items,
$j, $j+1);
}
}
}
return $items;
}
function arraySwap
(&$arr, $index1,
$index2) {
list($arr[$index1],
$arr[$index2])
= array($arr[$index2],
$arr[$index1]);
}
Summary : This
algorithm works by running through the array and swapping a value for the next
value along if that value is less than the current value. After the first run
through the highest value in the array will be at the correct end. It therefore
must run through the array once for every item in the array, so it has a low
efficiency.