Selection Sort Animation
–
Waiting for input...
Color: Compare • Swap • Processing • Sorted
See selection sort find the minimum element and place it in each pass.
Time O(n²) · Space O(1) · Unstable
Waiting for input...
Color: Compare • Swap • Processing • Sorted
def selection_sort(arr: list[int]) -> list[int]:
if arr is None or len(arr) == 0:
raise ValueError("Array is empty")
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
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.