一个有序的数列,使用折半查找效率更高。
先把要查找的值和数列的中间值进行比较,如果二者相等,我们找到了要查找的值。如果要查找的值小于中间值,说明要查找的值在数列的左侧。此时,令数列的右边界为中间值减去1,重新计算中间值。直到找到要寻找的值。如果数列的左边界大于右边界,说明要找的值不在次数列中。如果要查找的值大于中间值,说明要查找的值在数列的右侧。此时,令数列的左边界为中间值减去1,重新计算中间值。直到找到要寻找的值。如果数列的左边界大于右边界,说明要找的值不在次数列中。
代码如下
#include<stdio.h>
#include <stdlib.h>
int bin_search(int arr[], int key, int left, int right)
{
int mid = 0;
while (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] >key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return -1;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int key = 0;
int len = sizeof(arr) / sizeof(arr[0]);
int ret = 0;
int left = 0;
int right = len - 1;
//printf("%d", len);
scanf_s("%d", &key);
ret = bin_search(arr, key, left, right);
if (ret == -1)
{
printf("没找到\n");
}
else
printf("找到了,位置为%d\n", ret);
system("pause");
return 0;
}
用递归实现,代码如下
#include<stdio.h>
#include <stdlib.h>
int bin_search(int arr[], int key, int left,int right)
{
int mid = 0;
if (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] > key)
{
right = mid - 1;
bin_search(arr, key, left, right);
}
else
{
left = mid + 1;
bin_search(arr, key, left, right);
}
}
else
{
return -1;
}
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int key = 0;
int len = sizeof(arr) / sizeof(arr[0]);
int ret = 0;
int left = 0;
int right = len-1;
//printf("%d", len);
scanf_s("%d", &key);
ret =bin_search(arr,key,left,right);
if (ret == -1)
{
printf("没找到\n");
}
else
printf("找到了,位置为%d\n", ret);
system("pause");
return 0;
}