Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views8 pages

Binary Search for C++ Programmers

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Binary Search for C++ Programmers

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Lec-2

Binary Search
Binary search is a searching algorithm for a sorted collection of data.
It divides the range to search by half every iteration.

Time complexity: O(logn)


Takes ~20 iterations to search 106 elements
Implementation 1
Checks if target is present in the array
Implementation 2
Finds the last index of target
Lower bound and upper bound in STL

upper_bound() and lower_bound() are standard library functions in C++.

upper_bound() returns an iterator pointing to the first element in the range


[first, last) that is greater than the value. If no such an element is found,
return end(). ex. Ub = upper_bound(v.begin(), v.end(), value);

lower_bound() returns an iterator pointing to the first element in the range


[first, last) which is greater or equal to the value. If no such an element is
found, return -1. ex. Lb = lower_bound(v.begin(), v.end(),value);

**upper bound return first element which is > value. If not, return end().
**lower bound return first element which is ≥ value. If not, return end().

You might also like