Selection Sort
๐ Problem Statement
Given an unsorted array of integers, sort it in ascending order using Selection Sort. Modify the array in-place ( extra space). Input: [64, 25, 12, 22, 11] โ Output: [11, 12, 22, 25, 64]. Do not use built-in sort functions.
๐ก Intuition
Selection Sort divides the array into a sorted portion (left) and an unsorted portion (right). In each iteration, find the minimum of the unsorted portion and swap it to the front. After passes, one more element is permanently placed โ the key idea is "select the minimum and place it correctly."
๐ง Approach
- Iterate through the array from index to .
- Assume
arr[i]is the minimum. Scan the remaining unsorted portion ( to ) to find the true minimum index. - Swap
arr[i]witharr[min_index]. - Repeat until the entire array is sorted.
โก Complexity Analysis
in best, average, and worst cases โ always scans the remaining unsorted elements, even if already sorted
โ in-place, only a few extra variables
โ ๏ธ Common Mistakes
- Swapping inside the inner loop instead of after finding the minimum
- Forgetting to reset
min_indexfor every outer loop iteration - Assuming it becomes faster for already sorted arrays (it does not โ always )
- Confusing with Bubble Sort (Selection Sort minimizes swaps; Bubble Sort minimizes passes when optimized)
๐ฏ Final Thoughts
Selection Sort performs at most swaps, useful when write operations are costly. However, it always runs in regardless of input. Its value lies in understanding loop invariants and sorting logic before moving to algorithms like Merge Sort or Quick Sort.