对整形有序数组进行二分查找
#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 / 2;
if (k>arr[mid])
{
left = mid + 1;
}
if (k < arr[mid])
{
right = mid - 1;
}
if(k==arr[mid])
{
return mid;
}
}
return -1;
}
int main()
{
int k = 0;
printf("请输入要查找的数字");
scanf("%d", &k);
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int undernumber = find(arr, sz, k);
if (undernumber==-1)
{
printf("没找到!!!");
}
else
{
printf("找到了 下标为:%d", undernumber);
}
return 0;
}
运行结果: