Selection Sort

See selection sort find the minimum element and place it in each pass.

About Selection Sort

How Selection Sort Works

Selection sort divides the input into a sorted and unsorted region. It repeatedly selects the smallest element from the unsorted region and moves it to the end of the sorted region. While simple, it always performs O(n²) comparisons regardless of input order.

Scan the unsorted portion for the minimum element, then swap it with the first unsorted position. Advance the boundary between sorted and unsorted by one, and repeat until the entire array is sorted.

Complexity

Time
O(n²)
Space
O(1)
Stability
unstable

When to Use Selection Sort

  • Educational purposes
  • Situations where the number of swaps must be minimized
  • Small datasets where simplicity is preferred

Implementation

1def selection_sort(arr: list[int]) -> list[int]:
2    if arr is None or len(arr) == 0:
3        raise ValueError("Array is empty")
4    n = len(arr)
5    for i in range(n):
6        min_idx = i
7        for j in range(i + 1, n):
8            if arr[j] < arr[min_idx]:
9                min_idx = j
10        arr[i], arr[min_idx] = arr[min_idx], arr[i]
11    return arr
12

Selection Sort Animation

Waiting for input...

No steps to display. Please provide input to visualize the algorithm.

-