折半查找就是把数据分为一半,一半一半查找。
这样的查找效率比起顺序查找十分高效。
折半查找的条件:给出的数据是有序的。
下面给出折半查找的代码:
#include <stdio.h>
int BinSearch(int arr[], int length, int val)
{
int low = 0, high = length - 1, index = -1;
while (low <= high)
{
int mid = (low + high) / 2;
if (val == arr[mid])
{//查找成功index为下标
index = mid;
break;
}
else if (val > arr[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return index;
}
int main()
{
const int N = 10;
int A[N] = { 1,4,6,8,12,15,20,23,24,30 };
if (BinSearch(A, N, 14) != -1)
{
printf("查找成功");
}
else
{
printf("查找失败");
}
return 0;
}