Home > Sort algorithms > Selection Sort algorithm – PHP implementation

Selection Sort algorithm – PHP implementation

Algorithm:

  1. Find the smallest element in array and swap it with element from first position.
  2. Repeat first step with second smallest element and swap with element from second position.
  3. 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 n2 (n is array length): the number of comparisons between array elements is about n2/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(n2)
  • Average case: O(n2)
  • Best case: O(n2)

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:

  1. Introduction to Algorithms – Thomas H.Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein
  2. Algorithms – Robert Sedgewick
  3. http://en.wikipedia.org/wiki/Selection_sort
Advertisements
Categories: Sort algorithms Tags: , ,
  1. February 6, 2014 at 04:26

    Check out the following site for algorithms in PHP:
    http://AlgorithmsInPHP.com

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: