Overview
Data Structures
Searching
Selection Sort is a simple sorting algorithm that repeatedly selects the smallest (or largest) element from the unsorted part and places it at the beginning of the array.
Its time complexity is O(n²), making it inefficient for large datasets but useful for small lists or teaching purposes.
// Selection Sort in JavaScript
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let minIdx = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
}
return arr;
}
console.log(selectionSort([29, 10, 14, 37, 13])); // Output: [10, 13, 14, 29, 37]Start with an empty array of a chosen length. New slots start as NULL — fill them with Push or Insert below.
Finds the smallest value in the unsorted part and moves it to the front.