Insertion Sort Sample

Title: Insertion Sort: A Step-by-Step Guide with Mathematical Analysis Introduction Insertion Sort is a simple, comparison-based sorting algorithm that builds the final sorted array one item at a time. Although its worst-case running time is $O(n^2)$, it excels on nearly-sorted data and small arrays. In this article, we’ll walk through the algorithm, show its pseudocode, and derive the exact cost in terms of elementary summations. 1. Algorithm Intuition Imagine sorting a hand of playing cards: you remove one card at a time and insert it into its correct position among the already-sorted cards to your left. In an array $A[1 \dots n]$, we treat the prefix $A[1 \dots i-1]$ as sorted, then insert $A[i]$ into that prefix. 2. Pseudocode InsertionSort(A):  for i from 2 to n:   key ← A\[i]   j ← i – 1   # Shift elements of A\[1..i-1] that are greater than key to the right   while j ≥ 1 and A\[j] > key:    A\[j+1] ← A\[j]    j ← j – 1   end while   A\[j+1] ← key end for 3. Cost Model and Exact Count Let’s count the number of comparisons in the worst case (when the array is reverse-sorted). On the $i$th iteration, the inner `while` loop compares `key` against each of the $i-1$ elements, for a total of $$ \sum_{i=2}^{n} (i-1) =\;1 + 2 + \dots + (n-1) =\;\frac{n(n-1)}{2}. $$ Hence the total number of comparisons is $$ T_{\max}(n) =\frac{n(n-1)}{2} =\Theta(n^2). $$ Best case (already sorted): each inner loop does one comparison and exits immediately, so $$ T_{\min}(n) = n - 1 = \Theta(n). $$ Average case (assuming each new element goes to a random position in the sorted prefix) yields $$ T_{\mathit{avg}}(n) =\sum_{i=2}^{n}\mathbb{E}[\text{cost at step }i] =\sum_{i=2}^{n}\frac{i}{2} =\frac{1}{2}\sum_{i=2}^{n} i =\Theta(n^2). $$ 4. Space Complexity Insertion Sort is **in-place**: it only uses a constant amount of extra space beyond the input array. Thus $$ S(n)=O(1). $$ 5. When to Use Insertion Sort * **Small $n$**: For $n$ up to a few dozen, the low overhead beats more complex $O(n\log n)$ sorts. * **Nearly Sorted Data**: If the array is “almost” sorted, the algorithm runs in nearly linear time. * **Stable Sort Requirement**: It preserves the relative order of equal elements. 6. Example Walk-Through Given $[5, 2, 4, 6, 1, 3]$: 7. i=2: Insert 2 into \[5] → \[2, 5, 4, 6, 1, 3] 8. i=3: Insert 4 → \[2, 4, 5, 6, 1, 3] 9. i=4: Insert 6 → \[2, 4, 5, 6, 1, 3] (no moves) 10. i=5: Insert 1 → \[1, 2, 4, 5, 6, 3] 11. i=6: Insert 3 → \[1, 2, 3, 4, 5, 6] Conclusion Insertion Sort shines when your dataset is small or nearly sorted, offering simplicity, stability, and in-place operation. Its time complexity is governed by the classic triangular-number summation, $$ \sum_{i=1}^{n-1} i = \frac{n(n-1)}{2}, $$ making it a foundational algorithm for both teaching and practical edge-case sorting.