GATE Computer ScienceVery hardGATE CS (PYQ pattern)
Insertion sort on [7, 3, 9, 1, 8, 2, 6, 5, 4] scans left-to-right from position j = i − 1, comparing a[j] with the key until a[j] ≤ key or j falls below 0 (each such test is one comparison). How many key comparisons are made in total?
- A. 27
- B. 21
- C. 29
- D. 25
Correct answer: A. 27
Shifts equal the number of inversions, 21. Each of the 8 insertions also makes one terminating comparison (a[j] ≤ key), except when the scan runs off the left end, which happens when the key is a new minimum (keys 3 and 1): 21 + 8 − 2 = 27. Counting only inversions (21) forgets the terminating comparisons.
More Algorithms questions
- Lomuto partition (pivot = last element, loop j from lo to hi−1 comparing a[j] ≤ pivot) is used in quicksort on [5, 2, 8, 1, 9, 3, 7, 4…
- A randomised quicksort on a random permutation of n distinct keys picks a pivot uniformly and every partition of m elements costs exactly…
- Binary search on a sorted array of 20 distinct keys uses mid = ⌊(lo + hi)/2⌋ and one three-way comparison per probe, stopping when lo >…
- A base-3 (ternary) counter starts at 0 and is incremented 1000 times. The cost of an increment is the number of digits that change…
- A dynamic array starts with capacity 2. When it is full and an element is appended, the capacity becomes ⌈1.5 × capacity⌉ and all current…
- Consider t(n): if n ≤ 2 return 1; else return t(n−1) + t(n−2) + t(n−3). How many calls to t (including the initial call) are made when…