Home
> Sort algorithms > Selection Sort algorithm – PHP implementation

## Selection Sort algorithm – PHP implementation

**Algorithm:**

- Find the smallest element in array and swap it with element from first position.
- Repeat first step with second smallest element and swap with element from second position.
- Continue until array is sorted.

This is among the simplest of sorting method, and it will work very well for small files. Its running time is proportional with n^{2} (n is array length): the number of comparisons between array elements is about n^{2}/2, since the outer loop (on i) is executed n times and the inner loop (on j) is executed about n/2 times on average.

**Performance:**

- Worst case: O(n
^{2}) - Average case: O(n
^{2}) - Best case: O(n
^{2})

**PHP implementation** (function from a larger sort Class):

/**Function for sorting an array with selection sort algorithm. * * @param array $array * @return array */ public static function selectionSort(array $array) { for ($i=0;$i<count($array);$i++) { $min=$i; $length=count($array); for ($j=$i+1;$j<$length;$j++) { if ($array[$j]<$array[$min]) { $min=$j; } } $tmp=$array[$min]; $array[$min]=$array[$i]; $array[$i]=$tmp; } return $array; }

**Bibliography:**

**Introduction to Algorithms**– Thomas H.Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein**Algorithms**– Robert Sedgewick- http://en.wikipedia.org/wiki/Selection_sort

Advertisements

Categories: Sort algorithms
algorithm, PHP, sort

Check out the following site for algorithms in PHP:

http://AlgorithmsInPHP.com