Skip to content

Selection sort algorithm PHP implementation

2012 June 19
by Richard Knop

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
  1.  
  2. $arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
  3. $sortedArr = selectionSort($arr);
  4. var_dump($sortedArr);
  5.  
  6. function selectionSort(array $arr) {
  7.     for ($i = 0; $i < count($arr); ++$i) {
  8.         $min = null;
  9.         $minKey = null;
  10.         for($j = $i; $j < count($arr); ++$j) {
  11.             if (null === $min || $arr[$j] < $min) {
  12.                 $minKey = $j;
  13.                 $min = $arr[$j];
  14.             }
  15.         }
  16.         $arr[$minKey] = $arr[$i];
  17.         $arr[$i] = $min;
  18.     }
  19.     return $arr;
  20. }

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)
}
No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS