Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
Binary search: how many iterations does this loop run to find x = 23?
Binary search: how many iterations does this loop run to find x = 23?
a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
lo, hi, it = 0, len(a) - 1, 0
while lo <= hi:
it += 1
mid = (lo + hi) // 2
if a[mid] == 23: break
if a[mid] < 23: lo = mid + 1
else: hi = mid - 1
print(it, mid)- A. 3 5
- B. 2 5
- C. 1 5
- D. 4 5
Correct answer: A. 3 5
First mid = 4 (16 < 23) → lo = 5; second mid = (5 + 9)//2 = 7 (56 > 23) → hi = 6; third mid = (5 + 6)//2 = 5 → found. 3 iterations, within the ⌊log₂ 10⌋ + 1 = 4 worst case. Linear search would need 6 comparisons.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (run-length decode then re-encode) python import re enc = "a3b1c12" dec = "".join(ch int(n) for ch, n in…
- What is printed? (move zeros to the end keeping order) python a = [0, 1, 0, 3, 12, 0, 5] w = 0 for r in range(len(a)): if a[r] != 0: a[w]…
- What is the time complexity of deleting the last node of a singly linked list of n nodes when only a head pointer is kept?
- A stack is implemented with a singly linked list. Where should push and pop operate to keep both O(1)?
- What is printed? (C strings) c char s[] = "Placement"; printf("%zu %zu", strlen(s), sizeof(s));
- What is printed? (pointer arithmetic on an int array) c int a[] = {10, 20, 30, 40, 50}; int p = a + 1; printf("%d ", (p + 2)); printf("%d…