Selection Sort#

Selection Sort is an in-place, comparison-based sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of an array and swapping it with the first unsorted element. This shifts the boundary between the sorted and unsorted sections oen step to the right until the entire dataset is ordered.

Key Characteristics

In-Place Sorting

It modifies the original array directly without requiring extra storage structures.

Unstable by Default

It can change the relative order of duplicate elements during long-distance swaps.

Non-Adaptive Behavior

The algorithm executes the exact same number of steps regardless of initial order.

Brute-Force Mechanism

It scans the remaining unsorted list fully during every single iteration.

Minimal Swapping Operations

It performs a maximum of \(O(n)\) swaps, making it highly efficient when memory write cycles are costly.

Complexity

Worst-Case Time Complexity: \(O(n^2)\) when nested loops scan the data.

Average-Case Time Complexity: \(O(n^2)\) for typical, random arrays.

Best-Case Time Complexity: \(O(n^2)\) even if the array is already sorted.

Auxiliary Space Complexity: \(O(1)\) because it sorts memory in-place.

How It Works

  1. Divide: Treat the array as two parts: sorted (initially empty) and unsorted (the entire array).

  2. Scan: Search the unsorted part to locate the smallest value.

  3. Swap: Swap this minimum value with the leftmost element of the unsorted part.

  4. Advance: Move the boundary line one position to the right.

  5. Repeat: Continue these steps until the unsorted part has only one element left.

Implementation#

#include <utility>

template <int size>
void selectionSort(int (&array)[size]) {
  int minimum_index;
  for (int i = 0; i < (size - 1); ++i) {
    minimum_index = i;
    for (int j = i + 1; j < n; ++j) {
      if (array[j] < array[minimum_index]) {
        minimum_index = j;
      }
    }
    std::swap(array[i], array[minimum_index]);
  }
}

int main() {
  int array[5] { 3, 1, 5, 2, 4 };
  selectionSort(array); // { 1, 2, 3, 4, 5 }
}