Theory
Selection Sort divides the array into sorted and unsorted parts. It repeatedly finds the smallest element in the unsorted part and places it at the beginning of that part. Its time complexity is O(n²).
Example
const numbers = [64, 25, 12, 22, 11];
for (let i = 0; i < numbers.length - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[j] < numbers[minIndex]) {
minIndex = j;
}
}
const temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
console.log(numbers);
Expected Output
[11, 12, 22, 25, 64]
Practice
Implement Selection Sort for an array of integers.
Interview Questions
- How does Selection Sort work?
- What is its time complexity?
- How many major selections are made?
- How is Selection Sort different from Bubble Sort?