Lesson 2 of 20
Selection Sort
Selection Sort
Selection Sort divides the array into a sorted region (left) and an unsorted region (right). Each pass finds the minimum element in the unsorted region and moves it to the end of the sorted region.
How It Works
- Find the minimum element in the unsorted portion
arr[i..n-1]. - Swap it with
arr[i]. - Advance
iby one — the sorted region grows. - Repeat until the entire array is sorted.
function selectionSort(arr) {
const a = [...arr];
for (let i = 0; i < a.length; i++) {
let minIdx = i;
for (let j = i + 1; j < a.length; j++) {
if (a[j] < a[minIdx]) minIdx = j;
}
[a[i], a[minIdx]] = [a[minIdx], a[i]];
}
return a;
}
Complexity
| Case | Time | Space |
|---|---|---|
| Best | O(n²) | O(1) |
| Average | O(n²) | O(1) |
| Worst | O(n²) | O(1) |
Unlike bubble sort, selection sort always makes exactly n-1 swaps, regardless of input order. This makes it useful when writes (swaps) are expensive.
Your Task
Implement selectionSort(arr) that returns a new array sorted in ascending order.
JavaScript loading...
Loading...
Click "Run" to execute your code.