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:
“It is the highest and most legitimate pride of an Englishman to have the letters M.P. written after his name. No selection from the alphabet, no doctorship, no fellowship, be it of ever so learned or royal a society, no knightship,not though it be of the Garter,confers so fair an honour.”
—Anthony Trollope (18151882)
“A cold and searching wind drives away all contagion, and nothing can withstand it but what has a virtue in it, and accordingly, whatever we meet with in cold and bleak places, as the tops of mountains, we respect for a sort of sturdy innocence, a Puritan toughness. All things beside seem to be called in for shelter, and what stays out must be part of the original frame of the universe, and of such valor as God himself.”
—Henry David Thoreau (18171862)