In this tutorial, we will learn a simple sorting algorithm - Selection Sort.
Given a list of numbers as shown below, please sort them in ascending order.
$numbers = [21,25,100,98,89,77];
Requirements:
Selection Sort works by maintaining a sorted sub-list, finding the smallest item from the master list and swap it to the last element of the sub-list until all items are sorted.
The sorted sub-list's length is increased by one, whereas the master list's length is shrunk by one after each swap.
Pseudocode of Selection Sort algorithm can be written as follows:
FOR each element of the master list indexed by i
Set current element of master list as the sub-list[i] element
Find the smallest item from the master list (staring from i)
Swap it with the last element of sub-list
END FOR
We need an outer FOR loop to iterate through the master list and an inner FOR loop to find the smallest item from the master list.
<?php
$masterList = [21, 25, 100, 98, 89, 77];
$subList = [];
for ($i = 0; $i < count($masterList); $i++) {
$subList[$i] = $masterList[$i];
// Find the smallest item
$smallestIndex = $i;
for ($j = $i; $j < count($masterList); $j++) {
if ($masterList[$j] < $masterList[$smallestIndex]) {
$smallestIndex = $j;
}
}
// Swap
$tmp = $subList[count($subList) - 1];
$subList[count($subList) - 1] = $masterList[$smallestIndex];
$masterList[$smallestIndex] = $tmp;
}
print_r($subList);
// Output:
/*
Array
(
[0] => 21
[1] => 25
[2] => 77
[3] => 89
[4] => 98
[5] => 100
)
*/
Take note that the inner loop starts from i.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.