Insertion Sort
๐ Problem Statement
Given an unsorted array of integers, sort it in ascending order using the Insertion Sort algorithm. Modify the array in-place ( extra space). Input: [12, 11, 13, 5, 6] โ Output: [5, 6, 11, 12, 13]. Constraint: You must strictly use the Insertion Sort logic. Do not use built-in sort functions.
๐ก Intuition
Think of sorting a hand of playing cards. You keep the sorted cards in your left hand and pick up one unsorted card at a time. You scan your sorted hand from right to left, shift the larger cards over to make room, and insert the new card into its correct position. The left side of the array is progressively built up as a fully sorted section.
๐ง Approach
- Iterate from index to (assume the first element at index 0 is already sorted).
- Store the current element in a variable called
item(this is the card you just picked up). - Use an inner loop pointer starting at to scan the sorted left portion backwards.
- While and the element
arr[j]is strictly greater thanitem, shift the element one position to the right (arr[j + 1] = arr[j]). - Once the loop stops, insert the
iteminto the vacated spot (arr[j + 1] = item).
โก Complexity Analysis
- Worst & Average Case: โ Occurs when the array is reverse sorted, requiring every element to be shifted to the very beginning.
- Best Case: โ Occurs when the array is already sorted. The inner
whileloop immediately fails, so no shifting happens.
โ Insertion Sort is an in-place algorithm requiring only a few variables (item, i, j).
โ ๏ธ Common Mistakes
- Forgetting the boundary check
j >= 0in thewhileloop, which will cause anIndexErrorwhen scanning past the front of the array. - Overwriting values instead of shifting them (forgetting to store
arr[i]in the temporaryitemvariable first). - Using
arr[j] >= iteminstead ofarr[j] > item. Using>=causes the algorithm to swap identical elements, which breaks the "stability" of the sort.
๐ฏ Final Thoughts
Insertion Sort is highly efficient for small datasets or arrays that are already partially sorted (it is an "adaptive" algorithm). It is also a "stable" sort, meaning duplicate elements retain their original relative order. While it shares the same worst-case time complexity as Bubble and Selection sort, its best-case makes it the fastest of the three in real-world, nearly-sorted scenarios.