(1)直接二分法查找
#include<stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int k = 7;
int sz = sizeof(arr)/sizeof(arr[0]);
int left = 0;
int right = sz-1;
while(left<=right)
{
int mid = left + (right-left)/2;
if(k==mid)
{
printf("找到了:%d\n",mid);
break;
}
else if(k<mid)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
if(left>right)
{
printf("找不到\n");
}
return 0;
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int k = 7;
int sz = sizeof(arr)/sizeof(arr[0]);
int left = 0;
int right = sz-1;
while(left<=right)
{
int mid = left + (right-left)/2;
if(k==mid)
{
printf("找到了:%d\n",mid);
break;
}
else if(k<mid)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
if(left>right)
{
printf("找不到\n");
}
return 0;
}
(2)对函数进行调用
#include<stdio.h>
void binary_search(int arr[],int k,int sz)
{
int left = 0;
int right = sz-1;
while(left<=right)
{
int mid = left + (right-left)/2;
if(k==mid)
{
printf("找到了:%d\n",mid);
break;
}
else if(k<mid)
{
right=mid-1;
}
void binary_search(int arr[],int k,int sz)
{
int left = 0;
int right = sz-1;
while(left<=right)
{
int mid = left + (right-left)/2;
if(k==mid)
{
printf("找到了:%d\n",mid);
break;
}
else if(k<mid)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
if(left>right)
{
printf("找不到\n");
}
}
int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9,};
int k = 7;
int sz = sizeof(arr)/sizeof(arr[0]);
binary_saerch(&arr[0],k,sz);
return 0;
}
{
left=mid+1;
}
}
if(left>right)
{
printf("找不到\n");
}
}
int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9,};
int k = 7;
int sz = sizeof(arr)/sizeof(arr[0]);
binary_saerch(&arr[0],k,sz);
return 0;
}
(3) 对函数进行优化
#include<stdio.h>
int binary_search(int arr[],int k,int sz)
{
int left =0;
int right=sz-1;
while(left<=right)
{
int mid=left+(right-left)/2;
if(arr[mid]==k)
{
return mid;
}
else if(arr[mid]>k)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
return -1;
}
int binary_search(int arr[],int k,int sz)
{
int left =0;
int right=sz-1;
while(left<=right)
{
int mid=left+(right-left)/2;
if(arr[mid]==k)
{
return mid;
}
else if(arr[mid]>k)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
return -1;
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int k =7;
int sz=sizeof(arr)/sizeof(arr[9])-1;
int ret = binary_search(arr,k,sz);
if(ret==-1)
{
printf("找不到\n");
}
else
{
printf("找到了 %d\n",ret);
}
return 0;
}
{
int arr[]={1,2,3,4,5,6,7,8,9};
int k =7;
int sz=sizeof(arr)/sizeof(arr[9])-1;
int ret = binary_search(arr,k,sz);
if(ret==-1)
{
printf("找不到\n");
}
else
{
printf("找到了 %d\n",ret);
}
return 0;
}