二分查找(折半查找)算法
二分查找是将一个有序数列不断地缩小一半。
#include<stdio.h>
int main()
{
int search(int a[],int n, int x);
int i,x,z;
int a[10];
printf("please enter ten number:");
for(i = 1; i <= 10; i++)
scanf("%d",&a[i]);
printf("please enter the number that need to search:");
scanf("%d", &x);
z = search(a,10,x);
if(z >= 0)
printf("The number %d is the %d element in the array\n", x, z);
else
printf("Don't search the number\n");
}
int search(int a[], int n, int x)
{
int low, mid, high;
low = 0;
high = n - 1;
while(low <= high)
{
mid = (low + high) / 2;
/*如果序号为mid的元素和x的值相等,就返回该数据的序号mid*/
if(a[mid] == x)
return mid;
/*如果a[mid] > x,x就在low与mid-1序号之间,就不必再去查找
后面的元素,因此让high=mid-1,查找low与mid-1序号之间的数据
*/
else if(a[mid] > x)
high = mid - 1;
/*如果a[mid] < x,x就在mid+1与high序号之间,让low = mid + 1
查找mid+1与high之间的数据。
*/
else
low = mid + 1;
}
return -1;
}
可以发现二分查找法要查找的数列必须是有序的。