Modify Binary Search in C++: fails when target value is immediately before midpoint of array
See original GitHub issueThe C++ Binary Search example fails for any input where the target value is immediately before the midpoint of array. (When the value is at v[v.size()/2-1]).
Here are some example inputs that fail (returning false when true would be expected):
"1, 2" "1""1, 2, 3" "1""1, 2, 3, 4" "2""1, 2, 3, 4, 5" "2""1, 2, 3, 4, 5, 6" "3""1, 2, 3, 4, 5, 6, 7" "3"
For the given example “1, 2” “1”, the code does the following:
- before the while loop:
start = 0end = 2
- while loop condition
start < endis true, so we enter the while loop:mid = 1v[1]is2, which greater than targetnum==1, so we setend=mid-1, which isend==0
- while loop condition
start < endis now false, becausestart==1andend==1, so we exit the while loop - the search target was not found, so we return “false”
To fix it:
end is an exclusive range limit, not inclusive, so setting end=mid-1 effectively skips an index.
line 94 ought to be end=mid and not end=mid-1.
I’d recommend adding one of these failing example inputs as a test case for all binary search implementations in all languages, since this is an algorithmic issue that could appear in any language.
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:7 (7 by maintainers)
Top Results From Across the Web
Implementing binary search of an array (article) - Khan Academy
Here's the pseudocode for binary search, modified for searching in an array. The inputs are the array, which we call array ; the...
Read more >Calculating mid in binary search - algorithm - Stack Overflow
Specifically, it fails if the sum of low and high is greater than the maximum positive int value (2^31 - 1). The sum...
Read more >How to write binary search correctly - Zeyuan Hu's page
Binary search is a straightforward algorithm to understand but it is ... the array, then the target value is present in the current...
Read more >6.4. The Binary Search - Runestone Academy
If the item we are searching for is less than the middle item, we can simply perform a binary search of the left...
Read more >Find the element that appears once in a sorted array
A Simple Solution is to traverse the array from left to right. Since the array is sorted, we can easily figure out the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Can you guide me a bit how to fix the testing part or add new test cases . provide any article link or something which I can refer .
@PennyMew i can make the necessary changes , can you assign it to me .