Most of the other answers use two for loops to sort an array. At first the code seemed fairly straight and even I thought of the same. But then I wanted to investigate further. How efficient is this method? So using an array of 10,000 values, I used the two for loops method and got an execution time of 7.5 seconds
This is way too much. I'm sure PHP can't be this sloppy. So next I tested the in-built PHP rsort()
function and got a time of 0.003 seconds.
Some research gave me the answer that PHP uses a quicksort algorithm to sort indexed arrays with a recursive function. I dug deeper and found a few examples of quicksearch for C++, Java etc. So, I replicated them in PHP, as follows:
/*
The main function that implements QuickSort
arr --> Array to be sorted,
low --> Starting index,
high --> Ending index
*/
function quickSort(&$arr, $low, $high)
{
if ($low < $high)
{
/* pi is partitioning index, arr[p] is now
at right place */
$pi = partition($arr, $low, $high);
// Separately sort elements before
// partition and after partition
quickSort($arr, $low, $pi - 1);
quickSort($arr, $pi + 1, $high);
}
return $arr;
}
function partition (&$arr, $low = 0, $high)
{
$pivot = $arr[$high]; // pivot
$i = ($low - 1); // Index of smaller element
for ($j = $low; $j <= $high-1; $j++)
{
// If current element is smaller than or
// equal to pivot
if ($arr[$j] <= $pivot)
{
$i++; // increment index of smaller element
swap($arr[$i], $arr[$j]);
}
}
swap($arr[$i + 1], $arr[$high]);
return ($i + 1);
}
function swap(&$a, &$b){
$t = $a;
$a = $b;
$b = $t;
}
The time taken by this algorithm came out be: 0.023 seconds. Not as fast as rsort()
but satisfactory.