Algorithm LogbookAlgorithm Logbook

Selection Sort

Sorting

๐Ÿ“‹ Problem Statement

Given an unsorted array of integers, sort it in ascending order using Selection Sort. Modify the array in-place (O(1)O(1) 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 NN passes, one more element is permanently placed โ€” the key idea is "select the minimum and place it correctly."

๐Ÿ”ง Approach

  1. Iterate through the array from index i=0i = 0 to Nโˆ’1N-1.
  2. Assume arr[i] is the minimum. Scan the remaining unsorted portion (i+1i+1 to Nโˆ’1N-1) to find the true minimum index.
  3. Swap arr[i] with arr[min_index].
  4. Repeat until the entire array is sorted.

โšก Complexity Analysis

Time

O(N2)O(N^2) in best, average, and worst cases โ€” always scans the remaining unsorted elements, even if already sorted

Space

O(1)O(1) โ€” in-place, only a few extra variables

โš ๏ธ Common Mistakes

  • Swapping inside the inner loop instead of after finding the minimum
  • Forgetting to reset min_index for every outer loop iteration
  • Assuming it becomes faster for already sorted arrays (it does not โ€” always O(N2)O(N^2))
  • Confusing with Bubble Sort (Selection Sort minimizes swaps; Bubble Sort minimizes passes when optimized)

๐ŸŽฏ Final Thoughts

Selection Sort performs at most NN swaps, useful when write operations are costly. However, it always runs in O(N2)O(N^2) regardless of input. Its value lies in understanding loop invariants and sorting logic before moving to O(NlogโกN)O(N \log N) algorithms like Merge Sort or Quick Sort.