Commit 4b7c11c
authored
Fix binary search to return first occurrence for duplicates
### Fix: Binary Search Incorrect Output for Duplicates
Previously, the binary_search function returned any matching index when duplicates were present.
This change modifies the implementation to return the **first occurrence** of the target element.
### Changes made:
- Introduced a `result` variable to track the first occurrence
- Continued searching in the left half after finding a match
- Updated final return to return `result` instead of immediate index
### Example:
Input: [1, 2, 2, 2, 3], target = 2
Output (before): could be 1, 2, or 3
Output (after): 1 (first occurrence)
This resolves issue: #138401 parent 3c88735 commit 4b7c11c
1 file changed
+4
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
202 | 202 | | |
203 | 203 | | |
204 | 204 | | |
205 | | - | |
| 205 | + | |
206 | 206 | | |
207 | 207 | | |
208 | 208 | | |
209 | 209 | | |
210 | | - | |
| 210 | + | |
| 211 | + | |
211 | 212 | | |
212 | 213 | | |
213 | 214 | | |
214 | 215 | | |
215 | | - | |
| 216 | + | |
216 | 217 | | |
217 | 218 | | |
218 | 219 | | |
| |||
0 commit comments