二分查找非递归与递归实现
程序员文章站
2024-03-19 15:41:04
...
#include <stdio.h>
int BinSearch(int *str, int sz, int key) //非递归
{
int left = 0;
int right = sz-1;
int mid;
while (left <= right)
{
mid = (left + right) / 2;
if (key < str[mid])
{
right = mid-1;
}
if (key > str[mid])
{
left = mid+1;
}
if (key == str[mid])
return str[mid];
}
printf("no this key\n");
return 0;
}
//int BinSearch(int *str, int left,int right ,int key)//mid的作用域
//{
// if (left <= right)
// {
// int mid = (left + right) / 2;
// if (key == str[mid])
// return str[mid];
// if (key < str[mid])
// return BinSearch(str,left,mid-1,key);
// if (key > str[mid])
// return BinSearch(str,mid+1,right,key);
// }
// printf("No this key\n");
// return 0;
//
//}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int sz = sizeof(arr) / sizeof arr[0];
int p = BinSearch(arr, 0,sz-1, 10);
printf("%d\n", p);
return 0;
}
上一篇: 线性查找与二分查找入门