Visualizer › Sorting
Selection Sort
Finds the smallest element of the unsorted part and swaps it to the front, growing the sorted part by one element each pass.
How it works
- Always makes n(n−1)/2 comparisons, even on sorted input.
- Makes at most n − 1 swaps — useful when writes are expensive.
- Not stable: equal elements can change order.
Complexity
- Best time: O(n²)
- Average time: O(n²)
- Worst time: O(n²)
- Extra space: O(1)
- Stable: no
Code (Python)
def selection_sort(a):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
return aPractise: Arrays problems