0% found this document useful (0 votes)
2 views7 pages

Binary Search

Binary search is an efficient algorithm for finding a target value in a sorted collection, operating with a time complexity of O(logn). It repeatedly divides the search range in half, and the document includes a sample implementation and conditions for its application. Additionally, it discusses handling interactive problems where responses to queries are received within a limited number of attempts.

Uploaded by

FUSION
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)
2 views7 pages

Binary Search

Binary search is an efficient algorithm for finding a target value in a sorted collection, operating with a time complexity of O(logn). It repeatedly divides the search range in half, and the document includes a sample implementation and conditions for its application. Additionally, it discusses handling interactive problems where responses to queries are received within a limited number of attempts.

Uploaded by

FUSION
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/ 7

Binary Search

- Srivaths P
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
Finds the last index of target
int search(vector<int> a, int target) {
int left = 0, right = a.size() - 1;

while (left < right) {


int mid = (left + right + 1) / 2;

if (a[mid] <= target) left = mid;


if (a[mid] > target) right = mid - 1;
}

return (a[left] == target) ? left : -1;


}
Binary Search Conditions
Binary search works on a set of elements where the “predicate”
function applied on it is as follows:

���…����…���

Binary search will move:


• L to mid when predicate is true.
• R to mid when predicate is false.
Alternative Binary Search
int l = min-1, r = max+1;
while (r-l > 1) {
int m = (l + r) / 2;
if (predicate(m))
l = m;
else
r = m;
}

// l is the last true


// r is the first false
Interactive Problems:
In interactive problems, you get answers for your queries. Output a
query, and an input will be given as the answer.

There will be a limit to the number of queries you can make.


Also note the format of the queries and use it properly.

https://codeforces.com/contest/1480/problem/C

Remove fastio and use endl when solving interactive problems.


Thanks for watching!

You might also like