Selection Sort is a simple sorting algorithm that divides an array into a sorted and an unsorted portion. It repeatedly selects the smallest value from the unsorted portion and moves it to the end of the sorted portion.
This algorithm is easy to understand, but not efficient for large datasets. It is mainly used for learning and small collections.
Selection Sort works by selecting the smallest remaining element:
Each pass places one element into its correct position.
function selectionSort(arr) {
const result = [...arr];
for (let i = 0; i < result.length; i++) {
let minIndex = i;
for (let j = i + 1; j < result.length; j++) {
if (result[j] < result[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
// Swap values
const temp = result[i];
result[i] = result[minIndex];
result[minIndex] = temp;
}
}
return result;
}
// Example usage
const values = [64, 25, 12, 22, 11];
console.log(selectionSort(values)); // [11, 12, 22, 25, 64]