GATE / CS ARCHIVE

GATE CSE 2003 / QUESTION 62

Insertion sort on inputs with few inversions

Algorithms · Searching, Sorting & Selection · Full GATE CSE 2003 paper

GATE 2003, Q62 2 marks · MCQ
Report issue

Searching, Sorting & Selection

Question 62, GATE 2003: For a permutation a1,...,an of n distinct integers, an inversion is an index pair i<j with ai>aj. What is insertion sort's worst-case time if inputs are restricted to permutations of 1,...,n with at most n inversions?
A. Θ(n²)  B. Θ(n log n)  C. Θ(n^1.5)  D. Θ(n)
Question 62, GATE 2003: For a permutation a1,...,an of n distinct integers, an inversion is an index pair i<j with ai>aj. What is insertion sort's worst-case time if inputs are restricted to permutations of 1,...,n with at most n inversions?
A. Θ(n²)  B. Θ(n log n)  C. Θ(n^1.5)  D. Θ(n)
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. In insertion sort, a larger element shifts right exactly when it is an inversion partner of the current key. Each original inversion causes one such shift and is then removed.
2. With I inversions, the inner loops therefore make I shifts. The n−1 outer iterations and their final failed/boundary tests add Θ(n) work, so total work is Θ(n+I).
3. The restriction I≤n gives O(n+n)=O(n). Reading and processing n entries still requires Ω(n), including an already sorted input.
4. Matching the upper and lower bounds gives Θ(n), D. The unrestricted reverse-order example has Θ(n²) inversions and is excluded here.

Solution: In standard insertion sort, shifting an earlier larger element past the current key removes exactly one inversion. Total shifts equal the input inversion count I, and outer-loop work plus terminating comparisons contributes Θ(n). Hence running time is Θ(n+I). With I≤n this is O(n), while scanning the n elements requires Ω(n), so the restricted worst case is Θ(n), option D.

Original paper, page 9