二分查找:从有序数组中查找某个数
//循环
int main()
{
int a = 39; //需要查找的数
int arr[10] = { 0,1,2,3,4,5,6,39,78,90 };
int* p = arr;
int left = 0;
int right = 9;
while (left <= right)
{
int mid = (left + right) / 2; //一定要封装在循环内部
if (p[mid] == a)
{
printf("%d\n", mid);
break;
}
else if (p[mid] > a)
{
right = mid - 1;
}
else if (p[mid] < a)
{
left = mid + 1;
}
}
return 0;
}
//递归
int Bin_search(int* p, int a, int left, int right)
{
int mid = (left + right) / 2;
if (p[mid] == a)
{
return mid;
}
else if (p[mid] > a)
{
return Bin_search(p, a, left, mid - 1);//可以直接使用传给Bin_search的形参a
}
else if (p[mid] < a)
{
return Bin_search(p, a, mid + 1, right);
}
else
{
return -1;
}
}
int main()
{
int a = 78; //需要查找的数
int arr[10] = { 0,1,2,3,4,5,6,39,78,90 };
int* p = arr;
int left = 0;
int right = 9;
int ret = Bin_search(p, a, left, right);
printf("%d\n", ret);
return 0;
}