数据结构与算法(C语言版)__二分查找

二分查找(折半查找)
数据必须先排序,排序之后才能进行二分查找
220= 100万(就是1M)
230= 10亿(就是1G)
二分查找速度非常快

#include<iostream>

using namespace std;

int BinarySearch(int *a, const int x, const int n);

int main(){
    int x[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int 结果;
    int num;
    num = 1;
    结果 = BinarySearch(x, num, 10);
    if (结果 < 0)
        cout << "没有找到!" << endl;
    else
        cout << "在x[" << 结果 << "]中找到" << num << endl;
    system("pause");
    return 0;
}
int BinarySearch(int *a, const int x, const int n){
    int low, high, mid;
    low = 0, high = n - 1;
    while (low <= high){
        mid = (low + high) / 2;
        if (a[mid] == x)
            return mid;
        else if (a[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return -1;
}

使用下面的函数也是可以的。

int BinSearch(int *a, const int x, const int n){
    int left = 0, right = n-1;
    while(left<=right){
        int middle = (left+right)/2;
        if(x < a[middle])right = middle - 1;
        else if (x > a[middle])left = middle + 1;
        else return middle;
    }
    return -1;
}

总结:二分查找算是计算机里面最快的查找方法。但是对数据的要求是数据已经排序。数据没有排序就只能顺序查找。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值