ProgrammingVery hard
A sorted array of records is searched for the first record whose key is at least x (a lower bound). Which loop is correct?
- A. lo = 0; hi = n; while (lo < hi) { mid = (lo + hi) / 2; if (a[mid].key <= x) lo = mid; else hi = mid; }
- B. lo = 0; hi = n; while (lo < hi) { mid = lo + (hi - lo) / 2; if (a[mid].key < x) lo = mid + 1; else hi = mid; }
- C. lo = 0; hi = n - 1; while (lo <= hi) { mid = (lo + hi) / 2; if (a[mid].key < x) lo = mid; else hi = mid - 1; }
- D. lo = 0; hi = n; while (lo < hi) { mid = (lo + hi) / 2; if (a[mid].key > x) lo = mid + 1; else hi = mid; }
Correct answer: B. lo = 0; hi = n; while (lo < hi) { mid = lo + (hi - lo) / 2; if (a[mid].key < x) lo = mid + 1; else hi = mid; }
The half-open range [lo, hi) shrinks to the first index with key >= x, and mid = lo + (hi - lo) / 2 avoids overflow. The other versions answer upper bound or loop forever.
More C Programming questions
- An array of 2 x 10^5 records must be answered with 2 x 10^5 queries, each asking how many records have key <= q. Which approach is correct…
- After removing duplicate keys from a sorted array of records with the two-index method (keep a[w] when its key differs from the last kept…
- Bubble sort on the records of 4 keys {4, 3, 2, 1} with a swap count: how many swaps are made?
- A struct array holds records with an int key; the program calls qsort with the comparator (int)(a->key - b->key) for keys near INTMAX and…
- A bsearch call uses a key of type int but the array holds struct records with an int field. What is the correct way to compare?
- Which comparator for qsort on int array is correct for ALL int values (no overflow, no wrong sign)?