Selection Sort - Code

Implementation and analysis.


function selectionSort(arr):
    n = arr.length
    for i from 0 to n-2:
        minIdx = i
        for j from i+1 to n-1:
            if arr[j] < arr[minIdx]:
                minIdx = j
        swap(arr[i], arr[minIdx])

Time: O(n2)O(n^2) always. The inner loop runs n1,n2,...,1n-1, n-2, ..., 1 times regardless of input.

Space: O(1)O(1). Only a few variables for indices(except for the memory array itself).

Stability: Stable. Equal elements maintain their relative order.

Selection sort is simple but slow. Use it only for tiny arrays or when swaps are expensive (since it does exactly n1n-1 swaps).