题目:用递归和非递归两种方法实现二分查找
非递归法:
int binary_search(int *arr, int lenth, int key)
{
assert(arr != NULL);
int left = 0;
int right = lenth - 1;
int mid = 0;
while (left <= right)
{
mid = left + ((right - left) >> 1);//效率高且没有溢出问题
if (key > arr[mid])
{
left = mid + 1;
}
else if (key < arr[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;//找不到返回-1
}
void test()//测试部分
{
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int lenth = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", binary_search(arr, lenth, 0));
printf("%d\n", binary_search(arr, lenth, 1));
printf("%d\n", binary_search(arr, lenth, 2));
printf("%d\n", binary_search(arr, lenth, 3));
printf("%d\n", binary_search(arr, lenth, 4));
printf("%d\n", binary_search(arr, lenth, 5));
printf("%d\n", binary_search(arr, lenth, 6));
printf("%d\n", binary_search(arr, lenth, 7));
printf("%d\n", binary_search(arr, lenth, 8));
printf("%d\n", binary_search(arr, lenth, 9));
printf("%d\n", binary_search(arr, lenth, 10));
}
int main()
{
test();
system("pause");
return 0;
}
测试结果:
递归法:
int binary_search(int *arr, int left, int right, int key)
{
assert(arr != NULL);
if (left <= right)
{
int mid = left + ((right - left) >> 1);
if (key > arr[mid])
{
return binary_search(arr, mid+1, right, key);
}
else if (key < arr[mid])
{
return binary_search(arr, left, mid-1, key);
}
else
{
return mid;
}
}
else
{
return -1;
}
}
void test()
{
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int lenth = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", binary_search(arr, 0, 9, 0));
printf("%d\n", binary_search(arr, 0, 9, 1));
printf("%d\n", binary_search(arr, 0, 9, 2));
printf("%d\n", binary_search(arr, 0, 9, 3));
printf("%d\n", binary_search(arr, 0, 9, 4));
printf("%d\n", binary_search(arr, 0, 9, 5));
printf("%d\n", binary_search(arr, 0, 9, 6));
printf("%d\n", binary_search(arr, 0, 9, 7));
printf("%d\n", binary_search(arr, 0, 9, 8));
printf("%d\n", binary_search(arr, 0, 9, 9));
printf("%d\n", binary_search(arr, 0, 9, 10));
}
int main()
{
test();
system("pause");
return 0;
}
测试结果: