网上看了有些代码有些错误,主要是下面实例中的0查找不到,这里重新更正了下
思想:循环数组有一边是有序的,首先先判断哪一边有序(通过将当前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;
}
非递归写法如下:
#include<iostream>
#include<stdio.h>
#include<assert.h>
using namespace std;
int Binary_Search(int *A,int size,int value)
{
assert(A != NULL);
int low = 0;
int high = size - 1;
while(low <= high)
{
int mid = (low + high) / 2;
if(A[mid] == value)
return mid;
if(A[low] <= A[mid])//左有序,注意‘=’的使用
{
if(A[low] <= value && value <= A[mid])
high = mid - 1;
else
low = mid + 1;
}
else//右有序
{
if(A[mid] <= value && A[high] >= value)
low = mid + 1;
else
high = mid - 1;
}
}
}
int main()
{
int A[10] = {7,8,9,0,1,2,3,4,5,6};
cout<<Binary_Search(A,10,5);
return 0;
}