Selection Sort

Idea

Selection Sort repeatedly picks the minimum (or maximum) from the unsorted part and places it at the end of the sorted part until done.

Selection sort

Click "Step forward" to watch the algorithm state change.

Algorithm

  1. In each pass, find the minimum in the unsorted part and swap with its first element.
  2. Repeat n−1n-1 passes until fully sorted.

Pseudo-code:

for i = 0 to n-2:
    min = i
    for j = i+1 to n-1:
        if A[j] < A[min]:
            min = j
    if min != i:
        swap(A[i], A[min])

Code Implementation

void SelectSort(int A[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min = i;                     // the index of the smallest element
        for (int j = i + 1; j < n; j++) {
            if (A[j] < A[min]) min = j;  // found a smaller element
        }
        if (min != i) {                  // swap it into the end of the sorted part
            int tmp = A[i];
            A[i] = A[min];
            A[min] = tmp;
        }
    }
}

The Connection to Heap Sort

Simple selection sort has to scan the remaining part on every pass, so the number of comparisons is always n(n−1)2\frac{n(n-1)}{2}. Heap sort uses the heap structure to bring the cost of “finding the smallest element” down from O(n)O(n) to O(log⁡n)O(\log n), which lowers the overall complexity from O(n2)O(n^2) to O(nlog⁡n)O(n\log n).

Complexity

  • Best/worst/avg: O(n2)O(n^2)
  • Space: O(1)O(1)
  • Stability: unstable

Exercises

Exercise 1

Run selection sort on A=[64,25,12,22,11]A = [64, 25, 12, 22, 11] and show each pass.

Selection SortMinimum ElementPass

Approach: Each pass selects the smallest remaining element and moves it to the front.

Steps:

  1. Initial: [64, 25, 12, 22, 11]
  2. Pass 1: [11, 25, 12, 22, 64]
  3. Pass 2: [11, 12, 25, 22, 64]
  4. Pass 3: [11, 12, 22, 25, 64]
  5. Pass 4: [11, 12, 22, 25, 64]

Answer: As shown above; after every pass the minimum of the remaining suffix sits in its final position.

Exercise 2

What are the time and space complexities of selection sort?

Selection SortTime ComplexitySpace Complexity

Approach: Consider the time complexity and the extra space.

Steps:

  1. Time complexity O(n2)O(n^2)
  2. Space complexity O(1)O(1)

Answer: Time O(n2)O(n^2), space O(1)O(1).

Found an issue with this content?

Tell us what could be improved.