折半查找
二叉树看到线索二叉树就翻不动了,准备学一个简单地查找-二分查找。二分查找思想就是每次查找范围缩半,范围怎么缩的半?,我们通过改变数组的下标上限值或下限值来完成的,我们来看代码:
int binary_search (int *a,int n,int key) { int low=0; int height = n; int mid=n/2; while(low <= height) { mid = (low + height)/2; if(a[mid]<key) //使下限的值接近中间值 low = mid +1; else if(a[mid]>key) //使上限的值接近中间值 height = mid-1; else return mid; //返回结果,即当上限与下限相等的时候 } return 0; }
验证代码:
#include <iostream> using namespace std; int binary_search (int *a,int n,int key); int main() { int a[10]={2,3,4,5,6,7,8,9,12,13}; int search_num; for (int i = 0; i<10;i++) { cout<< a[i] <<endl; } cin>>search_num; cout<<binary_search (a,10,search_num)<<endl; getchar(); getchar(); return 0; }