如何让基于偏移量的二分查找在未找到元素时返回None?
Hey, great question—this is a fun twist on classic binary search! Let's break down how to implement this without relying on left or right pointers, and handle the "not found" case cleanly by returning None.
Core Idea
Instead of tracking the bounds of your search range with left/right, we'll use two variables:
pos: The starting offset of our current search windowstep: The size of the jump we'll make to narrow down the window (starts at half the array length, then halves each iteration)
We'll keep narrowing the search window by adjusting pos based on comparisons, until our step shrinks to 0. Then we just need to do one final check to confirm if we've found the target.
Implementation Code (Python)
def offset_binary_search(arr, target): if not arr: return None pos = 0 step = len(arr) // 2 while step > 0: # Avoid out-of-bounds checks (step will naturally shrink to prevent this) if pos + step < len(arr) and arr[pos + step] == target: return pos + step # Target is in the right half: move pos forward by step elif pos + step < len(arr) and arr[pos + step] < target: pos += step # Target is in the left half: keep pos unchanged step = step // 2 # Final check: after step hits 0, pos might be the target index return pos if arr[pos] == target else None
How It Works
Let's walk through a quick example to see the logic in action:
- Suppose
arr = [1,3,5,7,9,11]and target = 8:- Initial
pos = 0,step = 3(6//2) arr[0+3] =7 <8, so updateposto 3,stepbecomes 1arr[3+1] =9 >8, keepposat 3,stepbecomes 0- Loop ends, check
arr[3] =7 !=8, so returnNone
- Initial
If the target was 7, the first iteration would immediately find a match at pos+step = 3 and return that index.
Key Notes for Handling "Not Found"
- The loop runs until
stepis 0, which narrows our search down to a single candidate position (pos). - The final check is critical: it confirms whether that last remaining position holds the target. If not, we know the target isn't in the array, so return
None. - We added an upfront check for empty arrays to avoid index errors and immediately return
None.
This approach avoids left/right variables entirely, uses only offset-based logic, and correctly handles the "not found" case as you requested.
内容的提问来源于stack exchange,提问作者Sam

