May 2017
Intermediate to advanced
340 pages
8h 16m
English
We will take the same approach as the bubble sort where our implementation will take an array as an argument and return a sorted array. Here is the implementation in PHP:
function selectionSort(array $arr): array { $len = count($arr); for ($i = 0; $i < $len; $i++) { $min = $i; for ($j = $i+1; $j < $len; $j++) { if ($arr[$j] < $arr[$min]) { $min = $j; } } if ($min != $i) { $tmp = $arr[$i]; $arr[$i] = $arr[$min]; $arr[$min] = $tmp; } } return $arr;}
As can be seen, this is the simplest way to sort an array in ascending order. If you want to do it in descending order, we just need to change the comparison $arr[$j] < $arr[$min] to $arr[$j] > $arr[$min] and replace $min with $max.
Read now
Unlock full access