This post shows how to implement Selection Sort in JavaScript — a simple sorting algorithm that works by repeatedly selecting the smallest remaining element and moving it into place.
Selection sort in JavaScript:
Explanation:
Selection sort divides the array into a sorted part (at the beginning) and an unsorted part (the rest). On each pass, it scans the unsorted part to find the smallest element, then swaps it with the first unsorted position. This grows the sorted part by one element each pass until the whole array is sorted.
See Selection Sort in Action
Drag the slider to scrub through every comparison and swap, or use Play to watch it run automatically.
JavaScript Program to Implement Selection Sort
function selectionSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
const numbers = [29, 10, 14, 37, 14];
console.log("Sorted array:", selectionSort(numbers));
Output:
Sorted array: [ 10, 14, 14, 29, 37 ]
Selection sort makes far fewer swaps than bubble sort, which matters when swaps are expensive. Compare it with Heap Sort, which builds on a similar "find the extreme value" idea but far more efficiently. Try it yourself in our Code Runner.
Frequently Asked Questions About Selection Sort in JavaScript
What is the time complexity of selection sort?
Selection sort runs in O(n²) time in all cases — best, average, and worst — because it always scans the remaining unsorted elements to find the minimum, regardless of the input's initial order.
How is selection sort different from bubble sort?
Selection sort makes at most n swaps total, while bubble sort can make up to O(n²) swaps. Both have the same O(n²) time complexity overall, but selection sort is more efficient when writing/swapping data is costly.
Is selection sort a stable sorting algorithm?
No, not in its standard form. Swapping the minimum element into place can change the relative order of equal elements, though a modified version can be made stable at the cost of extra complexity.
