折半查找也叫二分查找,简单的理解就是每次只查找序列的一半,这样效率会很快,但是折半查找有个前提就是查找的序列必须是排好顺序的,不然没办法使用这个算法。
折半查找代码如下:
#include <stdio.h>
#define NOT_SEARCH -1
#define ARRAY_LEN 10
int binary_search(int *array,int array_len,int target);
int main(void)
{
int a[ARRAY_LEN] = {0,10,20,30,40,50,60,70,80,90};
int search_num;
int search_result;
printf("请输入要查找的数:");
scanf("%d",&search_num);
search_result = binary_search(a,ARRAY_LEN,search_num);
if(search_result > 0)
{
printf("找到该数,位于序列的第%d位。\n",search_result + 1);
}
else
{
printf("在该序列中找不到到该数!\n");
}
return 0;
}
int binary_search(int *array,int array_len,int target)
{
int low,mid,high;
low = 0;
high = array_len - 1;
while(low <= high)
{
mid = (low + high) / 2;
if(target < array[mid])
{
high = mid - 1;
}
else if(target > array[mid])
{
low = mid + 1;
}
else
{
return mid;
}
}
return NOT_SEARCH;
}