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)?

  1. A. (5, 3)
  2. B. (4, 3)
  3. C. (6, 3)
  4. 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}.

More Programming and Data Structures (GATE) questions

Exams that ask this topic