Files

79 lines
3.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: Binary Search(二分查找)
date: 2021-07-07 10:31:20
updated: 2021-10-05 13:53:00
tags:
- 算法
- 二分查找
categories: 算法
abbrlink: 52443
---
## 什么是二分查找?
二分查找(又称二分搜索)是一种算法;它的输入是一个已排序的元素列表。如果你要找的元素在这个列表中,二分查找返回它所在的位置。否则,二进制搜索返回**null**。
下图展示了二分查找法的用处:
![使用二分查找在电话簿中查找公司](/images/Algorithms/Binary-Search/使用二分查找在电话簿中查找公司.png)
下面的示例说明了二分查找的工作原理。我随便想一个1~100的数字。
![二分查找工作原理](/images/Algorithms/Binary-Search/二分查找工作原理.jpg)
你的目标是以最少的次数猜到这个数字。你每次猜测后,我会说小了、大了或对了。
假设你从1开始依次往上猜,猜测过程会是这样。
![一种糟糕的猜数法](/images/Algorithms/Binary-Search/一种糟糕的猜数法.png)
这是简单查找,更准确的说法是*傻找*。因为这种猜测,每次猜测都只能排除一个数字。如果我想的数字是99,你得猜99次才能猜到!
### 最佳的查找方式
下面的这种,则是更佳的查找方式。假设我们还是使用上面的1~100的数字作为例子,我们可以从中间开始。大家都知道1~100的中间是50。那我们就从50开始
![二分查找-从50开始](/images/Algorithms/Binary-Search/二分查找-从50开始.png)
这样,我们就知道,50以下的数字都是小了(1~50),与此同时,我们也排除了一半的数字。那接下来,我们就猜75。
![二分查找-从75开始](/images/Algorithms/Binary-Search/二分查找-从75开始.png)
这样,我们就知道,75以上的数字都是大了(1~75)。那剩下的数字,我们又排除了一半!当我们在使用二分查找的时候,你猜测的是中间的数字,从而每次都将剩下的数字排除一半。接下来,你猜63(50~75中间的数字)
![二分查找-正确的猜测](/images/Algorithms/Binary-Search/二分查找-正确的猜测.png)
这个,就是二分查找,也是第一种算法!我们每次猜测排除的数字个数如下:
![二分查找-排除个数](/images/Algorithms/Binary-Search/二分查找-排除个数.jpg)
不管我心里想的是哪个数字,你在7次之内都能猜到,因为每次猜测都将排除很多数字!
### 二分查找的执行代码
通过上面的那个例子,我相信大家都已经知道二分查找了,但是,我们怎么用代码实现呢?
先说一下,以下的代码,将会用Python进行。
```python
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = (low + high)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1, 3, 5, 7, 9]
print binary_search(my_list, 3) #=> 1 (Indexes start at 0)
print binary_search(my_list, -1) #=> None
```
以下的代码,将会用Java进行(代码来自:[图灵星球](https://turingplanet.org/2020/01/23/%e6%95%b0%e6%8d%ae%e7%bb%93%e6%9e%84%e5%92%8c%e7%ae%97%e6%b3%95%e7%ae%80%e4%bb%8b%e3%80%90%e6%95%b0%e6%8d%ae%e7%bb%93%e6%9e%84%e5%92%8c%e7%ae%97%e6%b3%951%e3%80%91/))
```java
public int binarySearch(int array[], int target) {
int left = 0;
int right = array.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid;
} else if (target < array[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
```