TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

Data Structure and Algorithm - Selection Sort

In this tutorial, we will learn a simple sorting algorithm - Selection Sort.

Problem to Solve

Given a list of numbers as shown below, please sort them in ascending order.

$numbers = [21,25,100,98,89,77];

Requirements:

  • You are required to use Selection Sort algorithm when sorting the numbers.
  • You are required to implement the algorithm in PHP language.

Pseudocode

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.

img

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

PHP Implementation

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.

The End

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.