2020-06-04 01:42:57 +00:00
|
|
|
---
|
|
|
|
slug: /silver/binary-search
|
2020-06-04 14:28:47 +00:00
|
|
|
title: "Binary Search"
|
2020-06-05 23:04:47 +00:00
|
|
|
author: Nathan Chen
|
2020-06-04 05:39:49 +00:00
|
|
|
order: 4
|
2020-06-05 00:37:02 +00:00
|
|
|
prerequisites:
|
|
|
|
-
|
|
|
|
- Silver - Sorting
|
2020-06-04 01:42:57 +00:00
|
|
|
---
|
|
|
|
|
2020-06-05 22:43:24 +00:00
|
|
|
Binary search can be used on monotonic functions for a logarithmic runtime.
|
2020-06-05 22:24:55 +00:00
|
|
|
|
2020-06-04 05:39:49 +00:00
|
|
|
<!-- END DESCRIPTION -->
|
2020-06-05 22:43:24 +00:00
|
|
|
|
2020-06-05 23:02:56 +00:00
|
|
|
## The Basic Application
|
|
|
|
|
|
|
|
Find an element in a sorted array in O(log N) time.
|
|
|
|
### Tutorial
|
2020-06-05 23:04:17 +00:00
|
|
|
- [GeeksForGeeks](https://www.geeksforgeeks.org/binary-search/)
|
|
|
|
- [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_algorithm)
|
2020-06-05 23:11:34 +00:00
|
|
|
### Library Functions to do Binary Search:
|
|
|
|
#### Java
|
|
|
|
- [Arrays.binarySearch](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html)
|
|
|
|
- [Collections.binarySearch](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html)
|
|
|
|
#### C++
|
|
|
|
- [lower_bound](http://www.cplusplus.com/reference/algorithm/lower_bound/)
|
|
|
|
- [upper_bound](http://www.cplusplus.com/reference/algorithm/upper_bound/)
|
2020-06-05 23:02:56 +00:00
|
|
|
### Problems
|
2020-06-05 23:04:17 +00:00
|
|
|
- [USACO Silver Counting Haybales](http://www.usaco.org/index.php?page=viewproblem2&cpid=666)
|
2020-06-05 23:02:56 +00:00
|
|
|
|
|
|
|
## Binary Searching on the Answer
|
2020-06-05 23:12:04 +00:00
|
|
|
Oftentimes used when you need to find the minimum or maximum of some quantity such that it satisfies some property.
|
2020-06-05 23:02:56 +00:00
|
|
|
### Tutorial
|
2020-06-05 23:04:17 +00:00
|
|
|
- [CPH Section 12.1](https://www.overleaf.com/project/5e73f65cde1d010001224d8a)
|
2020-06-05 23:02:56 +00:00
|
|
|
### Problems
|
2020-06-05 23:04:17 +00:00
|
|
|
- [USACO Silver Cownvention](http://www.usaco.org/index.php?page=viewproblem2&cpid=858)
|
|
|
|
- [USACO Silver Cow Dance](http://www.usaco.org/index.php?page=viewproblem2&cpid=690)
|
|
|
|
- [USACO Silver Social Distancing](http://www.usaco.org/index.php?page=viewproblem2&cpid=1038)
|
|
|
|
- [USACO Silver Loan Repayment](http://www.usaco.org/index.php?page=viewproblem2&cpid=991)
|
2020-06-05 23:02:56 +00:00
|
|
|
- Also needs some math and "sqrt" analysis
|
2020-06-05 23:04:17 +00:00
|
|
|
- [USACO Silver Angry Cows](http://usaco.org/index.php?page=viewproblem2&cpid=594)
|