B.Tech S3 (S) Examinations May 2026 (2024 Scheme)QP 06PCCST303112504Part B · Q10b3 marksCO1Module 4
Question 10b
Find the Best, Worst and average case time complexity of Insertion sort.
Topics: Insertion sort, Performance analysis: time and space complexity
Watch this exact question run
Loading visualizer…
Other parts: Worst case (reversed)
Solution
- Best case — input already sorted: the inner while test fails immediately in every pass, so exactly n − 1 comparisons and 0 shifts → O(n).
- Worst case — input in reverse order: pass i compares and shifts i elements, so 1 + 2 + … + (n − 1) = n(n − 1)/2 comparisons → O(n²).
- Average case — each new key moves past about half of the sorted part on average: ≈ n²/4 comparisons → O(n²).
| Case | Input | comparisons | shifts |
|---|---|---|---|
| Best (sorted) | 1, 2, 3, 4, 5, 6 | 5 | 0 |
| Worst (reversed) | 6, 5, 4, 3, 2, 1 | 15 | 15 |
| A random order | 4, 1, 6, 2, 5, 3 | 11 | 7 |
How to write it in the exam
| Case | Input | Comparisons | Complexity |
|---|---|---|---|
| Best | sorted | n − 1 | O(n) |
| Average | random | ≈ n²/4 | O(n²) |
| Worst | reverse sorted | n(n − 1)/2 | O(n²) |
How this answer was verified
- tests/sorting.test.ts (comparison counts 5 and 15 for n = 6)