1. 程式人生 > >淺談二分查找

淺談二分查找

字典 算法 pty 篩選 cannot block esp 登錄淘寶 arch

定義

In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array.

Binary search compares the target value to the middle element of the array;

if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful.

If the search ends with the remaining half being empty, the target is not in the array.

引用來自維基百科 Binary search algorithm

二分查找是一種搜索的算法,在有序數組中,根據目標值找到其位置。

比較目標值與數組的中間元素,如果不相等,不位於目標值的一半將會被淘汰,然後繼續在另一半中搜索直到找到為止。

如果另一半中搜索是空,那麽這個目標值不在數組中。

舉例

比如你要登錄淘寶,你的用戶名叫kk,那麽你登錄的時候,淘寶的數據庫要去搜索一下kk是否在其中,當然他不可能從a開始查起,應該從字典序的中間開始。小了,向後找,大了,向前找。

那麽再舉個例子,比方說,我在1 - 100 之間想一個數,你來猜,你的目標是盡可能少的次數來猜到這個數,然後我根據結果回復大了還是小了還是猜對了。

假如你從1開始遞增猜,如果我想的是99,你要猜99次。

換種思路,從一半的位置開始猜,就是50,如果回復小了,那麽結果就在51-100,直接排除掉前50個選項。依次進行,結果就只用7次就一定可以猜對。

我是怎麽得到7次的呢,每次篩選掉一半的值

7 > log2100

所以是7次。
也就是說這個算法的效率是

O(logn)

代碼

#include<iostream>
using namespace std;
int BinarySearch(int
a[], int n, int element) { int begin = 0, last = n - 1; int middle; while (begin <= last) { middle = (begin + last) / 2; if (element < a[middle])//查找的這個數小於中間值 last = middle - 1; else if (element > a[middle])//查找到這個數大於中間值 begin = middle + 1; else //相等返回索引 return middle; } return -1;//數組中沒有這個查找的值 } int main() { int n, a[100]; int digit; cout << "請輸入元素個數" << endl; cin >> n; cout << "請輸入各元素的值" << endl; for (int i = 0; i < n; i++) cin >> a[i]; cout << "請輸入要查找的值" << endl; cin >> digit; cout << "索引是"; cout << BinarySearch(a, n, digit)<<endl; return 0; }

淺談二分查找