const arr = [29, 10, 14, 37, 13]; // After first pass // After second pass // What is arr now?
Selection sort picks the smallest element and swaps it with the current position.
First pass swaps 29 with 10: [10, 29, 14, 37, 13]. Second pass swaps 29 with 13: [10, 13, 14, 37, 29].
Selection sort swaps only once per pass after finding the minimum.
Selection sort performs exactly n-1 swaps because it swaps the smallest element into place once per pass.
function selectionSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
const result = selectionSort([64, 25, 12, 22, 11]);
console.log(result);Selection sort sorts the array in ascending order by repeatedly selecting the smallest element.
The code correctly implements selection sort, resulting in the sorted array [11, 12, 22, 25, 64].
function selectionSort(arr) {
for (let i = 0; i <= arr.length; i++) {
let minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
return arr;
}
selectionSort([3, 1, 2]);Check the loop condition for i and how it affects array access.
The loop runs with i = arr.length, causing arr[i] to be undefined. Destructuring swap fails with TypeError.
Think about how many comparisons selection sort makes in total.
Selection sort uses two nested loops, each running up to n times, resulting in O(n^2) time complexity.