← Back to DSA
🎯

Sorting

Selection Sort

Repeatedly finds the minimum element from the unsorted portion and moves it to the sorted boundary.

Complexity

Time (Best)

O(n²)

Time (Avg)

O(n²)

Time (Worst)

O(n²)

Space

O(1)

Key Points

  • ›Makes exactly n−1 swaps regardless of input — useful when writes are expensive
  • ›Always O(n²) — does not benefit from pre-sorted data
  • ›In-place and simple to implement
  • ›Not stable by default (swapping can change relative order of equal elements)
  • ›Best suited for small arrays or when minimising swaps matters

Interactive Visualizer

Step 0 / 0✓ Sorted!
SlowFast
DefaultComparingSwappingSorted

Code Examples

Swift
func selectionSort(_ arr: inout [Int]) {
    let n = arr.count
    for i in 0..<n - 1 {
        var minIdx = i
        for j in i + 1..<n {
            if arr[j] < arr[minIdx] { minIdx = j }
        }
        if minIdx != i { arr.swapAt(i, minIdx) }
    }
}

var nums = [64, 25, 12, 22, 11]
selectionSort(&nums)
print(nums)  // [11, 12, 22, 25, 64]

Practice Problems

Sort Colors
Sort an Array