函数在整型有序数组中查找想要的数字(折半查找)
程序员文章站
2024-03-17 14:56:28
...
在整型有序数组中查找想要的数字, 找到了返回下标,找不到返回-1.(折半查找)
#include<stdio.h>
int Half(int a[], int n, int find)
{
int right = n - 1, left = 0;
int status = -1;
int mid;
while (left <= right)
{
mid = (right + left) / 2;
if (a[mid] == find)
{
status = mid;
break;
}
if (find < a[mid])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return status;
}
int main()
{
int a[] = { 1, 2, 4, 6, 7, 9, 14, 16, 17, 20 };
int find;
scanf("%d", &find);
printf("下标为: %d \n", Half(a, 10 , find));
system("pause");
return 0;
}
上一篇: 有序数组查找算法:二分法和插值法
下一篇: 移动端适配(简单的js代码搞定)