二分查找
算法要求:
1、必须采用顺序存储结构
2、必须按关键字大小有序排列
时间复杂度:
假设数组长度为n, 该算法时间复杂度为O(log(n))
代码区:
int binSearch(int Seq[],int len,int des)
{
int high=len-1;
int low=0,mid;
while(low<=high)
{
mid=low+(high-low)/2;
if(Seq[mid]==des)
return mid;
else if(Seq[mid]>des)
high=mid-1;
else low=mid+1;
}
return -1;
}
举个栗子:
#include <stdio.h>
#include <string.h>
#define LEN 5
int binSearch(int Seq[],int len,int des)
{
int high=len-1;
int low=0,mid;
while(low<=high)
{
mid=low+(high-low)/2;
if(Seq[mid]==des)
return mid;
else if(Seq[mid]>des)
high=mid-1;
else low=mid+1;
}
return -1;
}
int main()
{
int list[LEN];
int des,i;
printf("请输入要查找的数组:\n");
for(i=0;i<LEN;i++)
scanf("%d",&list[i]);
printf("请输入要查找的值:\n");
scanf("%d",&des);
printf("%d\n",binSearch(list,LEN,des));
return 0;
}