1.分析
1. 需要三个变量
1. nLow
2. nMid
3. nHigh
2. 过程
设待查数据为nFind, 数组为arr
如果 nFind > arr[nMid]
nLow = nMid + 1;
否则
nHigh = nMid - 1;
3. 时间复杂度: O(log^n)
#include<stdio.h>
#include<string.h>
int BinaryChop(int* arr, int nLen, int nFind)
{
if(arr == NULL || nLen <= 0)
return -1;
int nLow = 0;
int nHight = nLen -1 ;
int nMid = (nLow + nHight)/2;
while(nLow <= nHight)
{
if(nFind == arr[nMid])
{
return nMid;
}
else if(nFind < arr[nMid])
{
nHight = nMid - 1;
}
else
{
nLow = nMid + 1;
}
nMid = (nLow + nHight)/2;
}
return -1;
}
void Print(int arr[], int len)
{
for(int i=0; i< len;i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
void test(int* arr, int nLen, int nFind, int except)
{
int res = BinaryChop(arr,nLen,nFind);
if(except == res)
{
printf("Binary chop: %d is find in %d \n", nFind, res);
}
else
{
printf("Binary chop: %d is not in arr,res = %d \n",nFind,res);
}
}
int main()
{
int arr[] = {1,2,3,5,6,9,11,13,15,17,19,23,45,63,79,80,91,101};
int nLen = sizeof(arr)/sizeof(arr[0]);
Print(arr,nLen);
test(arr, nLen, 10,-1);
test(arr, nLen, 11,6);
test(arr, nLen, 19,10);
test(arr, nLen, 3,2);
return 0;
}