Selection Sort, explained step by step

Selection Sort is a simple comparison algorithm that divides the array into two sections: a sorted portion at the front and an unsorted portion at the back. It repeatedly scans the unsorted portion to find the absolute smallest element, and then swaps it with the first unsorted element. This process securely locks one more element into its final sorted position with every pass.

Intuition: Like sorting a hand of cards by always picking the smallest card from the remaining unsorted pile and placing it next.

How it works

  1. Assume the first unsorted element is the minimum (minIdx).
  2. Scan the rest of the unsorted array to find if there is a smaller element.
  3. If a smaller element is found, update minIdx to that element's index.
  4. After the scan, swap the minimum element found with the first unsorted element.
  5. The sorted boundary moves one step to the right. Repeat.

Complexity

  • Best: O(n²)
  • Average: O(n²)
  • Worst: O(n²)
  • Space: O(1)
  • Stable: no

When to use it

When memory writes are expensive (minimizes swaps). Otherwise, insertion sort is generally preferred.

Interview questions

  • Why is Selection Sort not stable by default?
  • Compare Selection Sort and Bubble Sort in terms of swaps.
  • Can Selection Sort be made stable?

Compare Selection Sort

Open Selection Sort in the visualiser