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
2020-06-07 07:38:45 +00:00
"Find an element in a sorted array in O(log N) time." This is a very basic form of binary search. Other variations are similar, like "Given K, find the largest element less than K in a sorted array."
2020-06-05 23:02:56 +00:00
### 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-07 07:38:45 +00:00
2020-06-05 23:02:56 +00:00
### Tutorial
2020-06-07 08:44:44 +00:00
- [Introduction to USACO Section 12.1 ](https://darrenyao.com/usacobook/java.pdf )
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 )