← Back

Selection Sort

comparisonin-placeunstable
Press play to start
1function selectionSort(arr: number[]): number[] {
2 for (let i = 0; i < arr.length - 1; i++) {
3 let minIdx = i
4 for (let j = i + 1; j < arr.length; j++) {
5 if (arr[j] < arr[minIdx]) {
6 minIdx = j
7 }
8 }
9 if (minIdx !== i)
10 [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]]
11 }
12 return arr
13}
Step 1/0
Custom array:

Complexity

Best:O(n²)
Average:O(n²)
Worst:O(n²)
Space:O(1)

Description

Divides the array into sorted and unsorted regions. Repeatedly finds the minimum element from the unsorted region and places it at the beginning.

When to use

Simple to implement. Use for small arrays where write operations are costly (minimizes swaps). Not suitable for large datasets.