Selection sort always performs the same number of comparisons regardless of the input array's order.
For random arrays, selection sort requires quadratic time.
Selection sort always performs the same number of comparisons and swaps regardless of the input array's order.
function selectionSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
// Find minimum element in unsorted part
let minIndex = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap found minimum with first element
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}