+ 6

Binary search in sorted duplicate values

Does normal binary search always gives first element in case duplicate value are present in sorted vector ?

12th Nov 2020, 5:40 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Respostas
+ 1
Ketan Lalcheta No, your implementation returns just some element - not necessarily the first one. Imagine, for example, that your array has all zeroes and you search for a zero, then a zero in the middle will be returned.
15th Nov 2020, 1:59 PM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
+ 9
If you mean std::binary_search, it returns bool telling if the value is in the sequence. There are also std::lower_bound, returning an iterator to the first element, std::upper bound, returning an iterator after the last element, and std::equal_range returning both. If your question is about implementing your own binary search, then it depends on how you implement it.
12th Nov 2020, 6:34 PM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
0
Thanks for response . I am concern about own implemented binary search. Please refer function named as implementBinarySearch() into code link https://code.sololearn.com/cWWWnWFAjdIy. For this case, does it always return lowest index in case our element to search is occurring more than once in sorted duplicate input?
15th Nov 2020, 1:51 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Yeah true example... Thanks
16th Nov 2020, 6:31 AM
Ketan Lalcheta
Ketan Lalcheta - avatar