1.0
#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int sz = sizeof(arr)/sizeof(arr[0]);
int k = 17;
int left = 0;
int right = sz - 1;
while(left<=right)
{
int mid = left + (right-left)/2;
if(arr[mid]>k)
right = mid -1;
else if(arr[mid]<k)
left = mid + 1;
else
{
printf("找到了,下标是:%d\n",mid);
break;
}
}
if(left>right)
{
printf("没找到\n");
}
return 0;
}
修改为有返回值的函数形式
#include <stdio.h>
int find(int arr[],int sz, int k)
{
int left = 0;
int right = sz - 1;
while(left<=right)
{
int mid = left + (right-left)/2;
if(arr[mid]>k)
right = mid -1;
else if(arr[mid]<k)
left = mid + 1;
else
{
return mid;
break;
}
}
if(left>right)
return -1;
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int sz = sizeof(arr)/sizeof(arr[0]);
int k = 0;
printf("请输入要查找的数字:");
scanf("%d",&k);
int tmp = find(arr,sz,k);
if (tmp!=-1)
printf("找到了,下标是:%d\n",tmp);
else
printf("没找到\n");
return 0;
}
不含返回值的函数形式
#include <stdio.h>
void find(int arr[],int sz, int k)
{
int left = 0;
int right = sz - 1;
while(left<=right)
{
int mid = left + (right-left)/2;
if(arr[mid]>k)
right = mid -1;
else if(arr[mid]<k)
left = mid + 1;
else
{
printf("找到了,下标是:%d\n",mid);
break;
}
}
if(left>right)
printf("没找到\n");
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int sz = sizeof(arr)/sizeof(arr[0]);
int k = 0;
printf("请输入要查找的数字:");
scanf("%d",&k);
find(arr,sz,k);
return 0;
}