Selection sort

From CodeCodex

Revision as of 20:17, 23 May 2007 by (Talk)

Related content:
50px See Wikipedia's Article for Selection sort.

Selection sort is a sorting algorithm, a comparison sort that works as follows:

  1. find the minimum value in the list
  2. swap it with the value in the first position
  3. sort the remainder of the list (excluding the first value)

It is probably the most intuitive sort algorithm to invent.

This algorithm, iterating through a list of n unsorted items, has a worst-case, average-case, and best-case run-time of Θ(n2), assuming that comparisons can be done in constant time. Among simple O(n2) algorithms, it is generally outperformed by insertion sort, but still tends to outperform contenders such as bubble sort and gnome sort.

Selection sort can be implemented as a stable sort. If, rather than swapping in step 2, the minimum value is inserted into the first position (that is, all intervening items moved down), this algorithm is stable (but slower). Selection sort is an in-place algorithm.

Heapsort greatly improves the basic algorithm by using an implicit heap data structure to speed up finding and removing the lowest datum.

A bidirectional variant of selection sort, called shaker sort, is an algorithm which finds both the minimum and maximum values in the list in every pass. Note, however, that shaker sort more often refers to a bidirectional variant of bubble sort.



void selectionSort(int numbers[], int array_size)
  int i, j;
  int min, temp;

  for (i = 0; i < array_size-1; i++)
    min = i;
    for (j = i+1; j < array_size; j++)
      if (numbers[j] < numbers[min])
        min = j;
    temp = numbers[i];
    numbers[i] = numbers[min];
    numbers[min] = temp;

Original source: [1]

Common Lisp

This is a recursive version. It doesn't really swap the values, it just creates a new list from the old one and returns that.

(defun selection-sort (list)
  (when list
    (let ((minimum-element (reduce #'min list)))
      (cons minimum-element
            (selection-sort (remove minimum-element list :test #'equal))))))


public  void selectionSort(int data[],int n)
	// pre: 0<=n <= data.length
	// post: values in data[0..n-1] in ascending order  
	    int numUnsorted=n; // number of values not in order 
	    int index;       // general index 
	    int max;
	    int temp;
	    while (numUnsorted > 0)
	          //determine a maximum value in Array
	          for (index=1; index < numUnsorted; index++)
	            if (data[max] < data[index])
	          // swap data[max] and data[numUnsorted-1]
	          temp                = data[max];
	          data[max]           = data[numUnsorted-1];
	          data[numUnsorted-1] = temp;


The following function returns a pair of the smallest element in a list and the remaining list:

# let rec select x = function
    | [] -> x, []
    | h::t ->
        let x, h = if x<h then x, h else h, x in
        let x, t = select x t in
        x, h::t;;
val select : 'a -> 'a list -> 'a * 'a list = <fun>

The selection sort uses the "select" function to prepend each smallest element in turn:

# let rec sort = function
    | [] -> []
    | h::t -> match select h t with
      | h, t -> h::sort t;;
val sort : 'a list -> 'a list = <fun>

For example:

# sort [1;6;2;7;3;8;4;9;5];;
- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]


 def selection_sort(list):
   l=list[:]                  # create a copy of the list
   sorted=[]                  # this new list will hold the results
   while len(l):              # while there are elements to sort... 
       lowest=l[0]            # create a variable to identify lowest
       for x in l:            # and check every item in the list...
           if x<lowest:       # to see if it might be lower.
       sorted.append(lowest)  # add the lowest one to the new list
       l.remove(lowest)       # and delete it from the old one
   return sorted


def selectionsort(list)
  0.upto(list.size-1) do |start|
    min = start
    start.upto(list.size-1) do |i|
      min = i if list[i] < list[min]
    list[start], list[min] = list[min], list[start]


var nombres, limit : int
get nombres
get limit
var last, smaller, bigger : int := 0
var rann, sort: array 1 .. nombres of int
for i : 1 .. nombres
    rann (i) := Rand.Int (0, limit)
end for
for v : 1 .. upper (rann)
    bigger := limit
    for b : 1 .. upper (rann)
        if rann (b) < bigger then
            last := b
            bigger := rann (b)
        end if
    end for
    sort (v) := rann (last)
    rann (last) := limit
end for
for b : 1 .. upper (sort)
    put " ", sort (b) ..
end for