Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
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
Example run (generated)checked by code
Input5 2 4 6 1 3
After pass 12 5 4 6 1 3
After pass 22 4 5 6 1 3
After pass 32 4 5 6 1 3
After pass 41 2 4 5 6 3
After pass 51 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