Selection Sort

In computer science, a selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list.

Here is an example of this sort algorithm sorting five elements:

64 25 12 22 11 11 25 12 22 64 11 12 25 22 64 11 12 22 25 64 11 12 22 25 64

(nothing appears changed on this last line because the last 2 numbers were already in order)

Selection sort can also be used on list structures that make add and remove efficient, such as a linked list. In this case it is more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far. For example:

64 25 12 22 11 11 64 25 12 22 11 12 64 25 22 11 12 22 64 25 11 12 22 25 64 /* a to a is the array to sort */ int i,j; int iMin; /* advance the position through the entire array */ /* (could do j < n-1 because single element is also min element) */ for (j = 0; j < n-1; j++) { /* find the min element in the unsorted a */ /* assume the min is the first element */ iMin = j; /* test against elements after j to find the smallest */ for ( i = j+1; i < n; i++) { /* if this element is less, then it is the new minimum */ if (a < a) { /* found new minimum; remember its index */ iMin = i; } } /* iMin is the index of the minimum element. Swap it with the current position */ if ( iMin != j ) { swap(a, a); } }

Read more about Selection Sort:  Mathematical Definition, Analysis, Comparison To Other Sorting Algorithms, Variants

Famous quotes containing the words selection and/or sort:

    Judge Ginsburg’s selection should be a model—chosen on merit and not ideology, despite some naysaying, with little advance publicity. Her treatment could begin to overturn a terrible precedent: that is, that the most terrifying sentence among the accomplished in America has become, “Honey—the White House is on the phone.”
    Anna Quindlen (b. 1952)

    The soul’s a sort of sentimental wife,
    That prays and whimpers of the higher life.
    Richard Le Gallienne (1866–1947)