Selection sort
Hey there! Let me explain selection sort in a way that'll actually make sense. You know how you sort your playing cards? You probably look through all your cards, find the smallest one, and put it first. Then you look through the remaining cards, find the smallest one again, and put it second. That's basically selection sort!
How Does It Work? š¤
Imagine you have a messy shelf of books arranged by height. Here's how you'd use selection sort to organize them:
Look at ALL the books
Find the shortest one
Put it on the far left
Repeat with the remaining books
That's it! Each time, you're "selecting" the smallest element (hence the name "selection sort").
Let's See It in Code! š»
Here's how we write selection sort in JavaScript:
function selectionSort(arr) {
const n = arr.length;
for(let i = 0; i < n; i++) {
// Assume the first unsorted element is the minimum
let minIndex = i;
// Look through the rest of the array for a smaller element
for(let j = i + 1; j < n; j++) {
if(arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// If we found a new minimum, swap it with the first unsorted position
if(minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
// Let's try it out!
let numbers = [64, 34, 25, 12, 22];
console.log(selectionSort(numbers)); // [12, 22, 25, 34, 64]
Let's Break It Down With a Real Example š
Say we have these numbers: [64, 34, 25, 12, 22]
First pass:
Look through all numbers
Find smallest (12)
Swap 12 with 64
Array becomes: [12, 34, 25, 64, 22]
Second pass:
Look through remaining numbers
Find smallest (22)
Swap 22 with 34
Array becomes: [12, 22, 25, 64, 34]
And so on... until everything's sorted!
The Good and The Bad šš
Advantages:
Simple to understand (like, really simple!)
Works well with small lists
Only makes one swap per pass through the array
Works well when memory writing is expensive
Disadvantages:
Takes the same amount of time regardless of how sorted the data already is
Not great for large lists
Slower than more advanced algorithms like quicksort
The Technical Stuff š¤
Time Complexity:
Best Case: O(n²) - yep, even when sorted!
Average Case: O(n²)
Worst Case: O(n²)
Space Complexity:
O(1) - it sorts in place, so it only needs a tiny bit of extra memory
When Should You Use It? šÆ
Selection sort is great when:
You have a small list to sort
You want to minimize the number of swaps
You're teaching someone about sorting algorithms
Memory space is tight
Happy sorting! š
last updated: 21-October-2024