B.Tech S3 (R) (FT/WP) Examination November 2025 (2024 Scheme)QP 06PCCST303112503Part A · Q83 marksCO4Module 4
Question 8
Write algorithm to sort an array using insertion sort.
Topics: Insertion sort
Watch this exact question run
Loading visualizer…
Solution
algorithm
Algorithm InsertionSort(a, n)
1. for i ← 1 to n − 1 do
2. key ← a[i]
3. j ← i − 1
4. while j ≥ 0 and a[j] > key do
5. a[j + 1] ← a[j]
6. j ← j − 1
7. a[j + 1] ← key
8. end| Input | 5 2 4 6 1 3 |
|---|---|
| After pass 1 | 2 5 4 6 1 3 |
| After pass 2 | 2 4 5 6 1 3 |
| After pass 3 | 2 4 5 6 1 3 |
| After pass 4 | 1 2 4 5 6 3 |
| After pass 5 | 1 2 3 4 5 6 |
Totals: comparisons = 12, shifts = 9
How to write it in the exam
Best case O(n) (sorted input), worst and average O(n²); in-place, stable.
How this answer was verified
- Property tests
- insertion_sort.c differential test