GATE Computer ScienceVery hardGATE CS
Hoare partition on a[0..8] = {8, 3, 9, 1, 8, 5, 2, 7, 6}: int hoare(int a[], int lo, int hi) { int p = a[lo], i = lo - 1, j = hi + 1; while (1) { do i++; while (a[i] < p); do j--; while (a[j] > p); if (i >= j) return j; swap(&a[i], &a[j]); } } Called as hoare(a, 0, 8), what is (the returned value, the number of swaps performed)?
- A. (5, 3)
- B. (4, 3)
- C. (6, 3)
- D. (5, 4)
Correct answer: A. (5, 3)
Pivot 8. Swap 1: a[0] and a[8] (8, 6). Swap 2: a[2] = 9 and a[7] = 7. Swap 3: a[4] = 8 and a[6] = 2. Then i stops at 6 and j at 5, so i ≥ j and the function returns 5 with the array {6, 3, 7, 1, 2, 5, 8, 9, 8}.
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- A singly linked list has a tail of 6 nodes leading into a cycle of 9 nodes. A pointer 'slow' moves 1 node per step and a pointer 'fast'…
- An open-addressing table of size 11 uses h(k) = k mod 11 with linear probing and tombstones. Insertion places the key in the first empty…
- A sparse table for range-minimum queries on an array of 1000 elements stores, for each level k = 0, 1, ..., ⌊log₂ 1000⌋, one entry for…
- A segment tree over positions 0 to 12 (13 elements) is built recursively: the root is node 1, the node for [lo, hi] splits at mid = (lo +…
- A B-tree with minimum degree t = 3 (every node except the root has between 2 and 5 keys) is built with the CLRS insertion procedure, which…
- Items 1, 2, 3, 4, 5 arrive in this order and are inserted, each at either the front or the back of a double-ended queue (the choice is…