1.折半查找又叫二分查找,仅适用于顺序表。
2
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int binary_search(int arr[], int leg,int key)
{
int low = 0, high = leg - 1,mid;
while (low <= high)
{
mid=(low+high)/2;
if (arr[mid]== key)
{
return mid;
}
else if (arr[mid] > key)
{
high=mid-1;
}
else
{
low = mid + 1;
}
}
return -1;
}
int main()
{
int arr[10] = { 0,1,2,3,4,5,6,7,9,10 };
int leg = sizeof(arr);
int x=binary_search(arr,leg,8);
printf("%d\n", x);
return 0;
}