码迷,mamicode.com
首页 > 其他好文 > 详细

浅谈二分查找

时间:2017-11-26 21:55:17      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:pre   位置   效率   get   bin   com   sub   sci   algorithm   

定义

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;
}

浅谈二分查找

标签:pre   位置   效率   get   bin   com   sub   sci   algorithm   

原文地址:http://www.cnblogs.com/pjc20/p/7900473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!