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:
“The books for young people say a great deal about the selection of Friends; it is because they really have nothing to say about Friends. They mean associates and confidants merely.”
—Henry David Thoreau (18171862)
“My father and I were always on the most distant terms when I was a boya sort of armed neutrality, so to speak. At irregular intervals this neutrality was broken, and suffering ensued; but I will be candid enough to say that the breaking and the suffering were always divided up with strict impartiality between uswhich is to say, my father did the breaking, and I did the suffering.”
—Mark Twain [Samuel Langhorne Clemens] (18351910)