Selection Sort

File:Sorting selection sort anim.gif

Reference: https://commons.wikimedia.org/wiki/File:Sorting_selection_sort_anim.gif

The Selection Sort locates the minimal, or smallest, element in an array A and swaps it out with A[0]. After that, the sort ignores A[0] and moves on to the next minimum, or smallest, replacing A[0] with A[1] and so forth.

Two sub-arrays are maintained in a given array by the Selection Sort method.

1. The sub-array has already been sorted.
2. Remaining sub-array, unsorted.

An example of Selection Sort

If A = [12, 8, 11, 4, 2, 9]

[12, 8, 11, 4, 2, 9] //find a smallest element, is 2
[2, 8, 11, 4, 12, 9] //smallest element 2 swap with A[0] and find next smallest element, is 4
[2, 4, 11, 8, 12, 9] //next smallest element 4 swap with A[1] and find next smallest element, is 8
[2, 4, 8, 11, 12, 9] //here smallest element 8 swap with A[2] and find next smallest element, is 9
[2, 4, 8, 9, 12, 11] //now smallest element 9 swap with A[3] and find smallest element in rest of array is 11
[2, 4, 8, 9, 11, 12] //sorted

The iterative Selection Sort algorithm

//Sort the first n elements of an array
Input: array A, int n
Output:
selectionSort1(A, n){
    for(index = 0; index<n-1; index++){
        indexOfNextSmallest = the index of the smallest value
        among A[index], A[index+1], …A[n-1]
        interchange the value of A[index] and A[indexOfNextSmallest]
    }
}

The recursive Selection Sort algorithm

//Sort the array elements A[first] through A[last] recursively
Input: array A, int first, int last
Output:
selectionSort2(A, first, last){
    if(first<last){
        indexOfNextSmallest = the index of the smallest value among
        A[first], A[first+1], …A[last]
        interchange the value of A[first] and A[indexOfNextSmallest]
        selectionSort2(A, first+1, last)
    }
}

Selection Sort running time analysis is O(n²) regardless of the initial order of the elements in an array.