Selection Sort
Selection sort is an in-place comparison sorting algorithm that divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list.
Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
Time Complexity
Worst-case:
O(n2)Average-case:
O(n2)Visualization
Canvas
Code
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let minIndex = i;
let minValue = arr[i];
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < minValue) {
minIndex = j;
minValue = arr[j];
}
}
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
return arr;
}Copied to clipboard!