Q.Consider a list [-4, 0, 2, 7, 8, 17, 19]. Apply binary search to find element -4. Determine the number of key comparisons required.
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Binary search efficiently finds an element in a sorted list by repeatedly dividing the search interval in half. To find -4 in the given list, it requires 3 key comparisons.
Binary search is an efficient algorithm for finding an element within a sorted list. Its core idea is to repeatedly divide the search interval in half. If the value of the search key is less than the item in the middle of the interval, the algorithm narrows the interval to the lower half. Otherwise, it narrows it to the upper half. This process continues until the value is found or the interval is empty.
For binary search to work, the list must be sorted. The given list [-4, 0, 2, 7, 8, 17, 19] is already sorted in ascending order, which is a prerequisite for applying binary search.
Let's trace the steps to find the element -4 in the list L = [-4, 0, 2, 7, 8, 17, 19].
We maintain three pointers: low (the starting index of the current search interval), high (the ending index of the current search interval), and mid (the middle index).
- Initial state:
low = 0(index of the first element)high = 6(index of the last element, since the list has 7 elements)target = -4comparisons = 0
Here is a step-by-step breakdown:
| Step | low | high | mid = (low + high) // 2 | L[mid] | Comparison (L[mid] vs target) | Action | comparisons |
| :--- | :---- | :----- | :------------------------ | :------- | :--------------------------------- | :----- | :------------ | …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.