Selection sort repeatedly finds the minimum element from the unsorted part of the array and swaps it with the first unsorted element.
Generate a new array or click Sort/Step Through.
Steps:
O(n²) - Requires nested loops to iterate through the array.
O(1) - Sorts in-place, requiring minimal extra memory.
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;
}