二分查找

来源:互联网 发布:cnc编程员 编辑:程序博客网 时间:2024/06/08 07:43
//二分查找//使用前提是数据已排序 ,否则需要用线性查找(顺序查找) //二分法是常见程序中最快的算法 //2^20=100万(就是1M)最多查找20次 //2^30=10亿(就是1G)最多查找30次  #include <iostream> using namespace std; int BinarySearch(int *list,const int n,const int x);  int main() { int a[]={0,1,2,3,4,5,6,7,8,9}; int result,num=5;  result=BinarySearch(a,10,num); if(result==-1)//或者if(result<0)cout<<"没有找到"<<endl;elsecout<<"在a["<<result<<"]找到"<<num<<endl;return 0; } int BinarySearch(int *list,const int n,const int x) { int low=0,high=n-1,mid;while(low<=high){mid=low+(high-low)/2;if(list[mid]==x)return mid;else if(list[mid]<x)low=mid+1;else high=mid-1;} return -1; } 

0 0