GATE Computer ScienceVery hardGATE CS (PYQ pattern)
Dutch-national-flag partition on a = [2, 0, 1, 2, 1, 0, 0, 2, 1, 1, 0, 2]: lo = mid = 0, hi = 11; while mid <= hi: if a[mid] == 0 { swap(a[lo], a[mid]); lo++; mid++; } else if a[mid] == 1 mid++; else { swap(a[mid], a[hi]); hi--; }. How many swap calls are made, and in how many of them are the two values exchanged actually different?
- A. 8 calls, 8 effective
- B. 8 calls, 4 effective
- C. 8 calls, 5 effective
- D. 7 calls, 5 effective
Correct answer: C. 8 calls, 5 effective
Trace: mid = 0 holds 2 and is swapped with a[11] = 2 (equal values); the new a[0] is again 2 and is swapped with a[10] = 0; then mid = 0 and mid = 1 hold 0 while lo == mid, so those swaps exchange an element with itself; later 2 <-> 1 at (3, 9), 1 <-> 0 at (2, 5) and (3, 6), and 2 <-> 1 at (7, 8). That is 8 swap calls (one per 0 and per 2, as expected), but 3 of them exchange equal values, leaving 5 that actually move data.
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- A heap with 2000 elements is stored in an array (complete binary tree, last level filled left to right). How many elements are in the left…
- How many structurally distinct AVL trees (left and right distinguished, shape only) have exactly 9 nodes?
- A binary tree is serialised in preorder with # for a null child: A B D # # E G # # # C # F # #. What is its inorder traversal and its…
- An undirected simple graph on 100 vertices is stored by keeping only the upper triangle (without the diagonal) of its adjacency matrix as…
- The 4 largest elements of the stream 14, 7, 22, 3, 18, 9, 30, 11, 25, 5, 17, 28, 2, 21 are found with a min-heap of size 4 holding the…
- A sorted array was rotated: [15, 18, 22, 25, 30, 2, 4, 7, 9, 11, 12, 14]. The standard rotated binary search (compare a[lo] <= a[mid] to…