PHP Selection Sort Algorithm

Wiki

Selection sort is another common sorting algorithm. You iterate n times over your list of numbers where n is the number of items in the list. In every iteration you find the minimum value in the list and switch its position with the first item in the list. In every iteration you will be looking for a minimum value in a list with n – i length where n is the number of items in the list and i is the number of the current iteration. In other words, in the first iteration you will use the full list, in the second iteration you will use a list without the first item, in the third iteration you will use a list without first two items and so on. It’s the same thing as using array_unshift every time after you find a minimum and place it on the beginning of the array.

Example

<?php
 
$arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
$sortedArr = selectionSort($arr);
var_dump($sortedArr);
 
function selectionSort(array $arr) {
    for ($i = 0; $i < count($arr); ++$i) {
        $min = null;
        $minKey = null;
        for($j = $i; $j < count($arr); ++$j) {
            if (null === $min || $arr[$j] < $min) {
                $minKey = $j;
                $min = $arr[$j];
            }
        }
        $arr[$minKey] = $arr[$i];
        $arr[$i] = $min;
    }
    return $arr;
}

Will result in

array(10) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
  [8]=>
  int(8)
  [9]=>
  int(9)
}
0.00 avg. rating (0% score) - 0 votes