标签:blog io os ar 2014 sp 代码 log c
网上看了有些代码有些错误,这里重新更正了下
思想:循环数组有一边是有序的,首先先判断哪一边有序(通过将当前mid点与最左边节点比较),然后查看是否在有序边上
代码如下
#include<iostream> #include<assert.h> using namespace std; int Binary_Search(int *a,int low,int high,int value) { int mid=(low+high)/2; if(a[mid] == value) return mid; if(a[mid]>=a[low]) //左有序 { if(a[low]<=value && value<a[mid]) //说明value在左边,直接二分查找 { return Binary_Search(a,low,mid,value); } else //value在右边 { return Binary_Search(a,mid+1,high,value); } } else //右有序 { if(a[mid]<=value && value<=a[high]) { return Binary_Search(a,mid,high,value); } else { return Binary_Search(a,low,mid-1,value); } } } int main() { int A[10] = {7,8,9,0,1,2,3,4,5,6}; int p = Binary_Search(A,0,9,0); cout<<p<<endl; return 0; }
标签:blog io os ar 2014 sp 代码 log c
原文地址:http://blog.csdn.net/cz28274815/article/details/39233485