Data Structures & AlgorithmsVery hardProduct company OA

One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)?

One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)?
def hoare(a):
    p = a[0]; i, j = -1, len(a)
    while True:
        i += 1
        while a[i] < p: i += 1
        j -= 1
        while a[j] > p: j -= 1
        if i >= j: return a, j
        a[i], a[j] = a[j], a[i]
print(hoare([6, 3, 9, 6, 1, 8, 2, 7]))
  1. A. ([2, 3, 1, 6, 6, 8, 9, 7], 4)
  2. B. ([2, 3, 1, 6, 9, 8, 6, 7], 3)
  3. C. ([1, 2, 3, 6, 6, 7, 8, 9], 3)
  4. D. ([2, 3, 1, 6, 9, 8, 6, 7], 4)

Correct answer: B. ([2, 3, 1, 6, 9, 8, 6, 7], 3)

i stops at elements ≥ pivot and j at elements ≤ pivot, then they swap. Round 1: i = 0 (6), j = 6 (2) → swap. Round 2: i = 2 (9), j = 4 (1) → swap. Round 3: i = 3 (6), j = 3 (6) → i ≥ j, return 3. Unlike Lomuto, Hoare does NOT put the pivot in its final place: the result only guarantees a[0..3] ≤ 6 ≤ a[4..7], and an equal 6 is left on each side. Recurse on [lo, j] and [j + 1, hi].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic