Selection sort
Selection sort is a simple comparison-based sorting algorithm. It works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and swapping it with the first unsorted element. This process continues until the entire list is sorted.
Steps
- Find the smallest element in the unsorted part of the list.
- Swap it with the first unsorted element.
- Move to the next unsorted element and repeat the process until all elements are sorted.
Selection sort has a time complexity of O(n²)
, making it less efficient for large lists, but it's easy to understand and implement.
Implementation
Basic Selection Sort
function selectionSort(arr) {
const n = arr.length;
// Loop through the entire array
for (let i = 0; i < n - 1; i++) {
// Assume the minimum is the first element of the unsorted part
let minIndex = i;
// Find the index of the minimum element in the unsorted part
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element of the unsorted part
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}