GATE Computer ScienceVery hardGATE CS (PYQ pattern)
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, 6], recursing on both sides until size ≤ 1. How many element-to-pivot comparisons are performed in total?
- A. 16
- B. 18
- C. 21
- D. 17
Correct answer: D. 17
Each partition call on m elements costs exactly m − 1 comparisons. Tracing the recursion, the calls have sizes 9, 5, 3, 2 and 3, costing 8 + 4 + 2 + 1 + 2 = 17.
More Algorithms questions
- 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…
- How many times is x++ executed? for (i = 2; i <= 100; i++) for (j = ii; j <= 100; j += i) x++;