二分(折半)查找算法练习
Time Limit: 1000 MS Memory Limit: 32768 K
Total Submit: 404 (216 users) Total Accepted: 230 (211 users) Special Judge: No
Description
在一个有序表中利用二分法查找某个关键字是否存在。
Input
输入为多组数据,每组为两行数据,每组中第一行为建立查找的顺序表,第二行是要查找的关键字。
Output
若找到关键字,则输出关键字在表中的位置,否则输出0.
Sample Input
1 2 3 4 5
10
1 2 3 4 5
5
Sample Output
0
5
#include<stdio.h>
#include<stdlib.h>
typedef int elep;
#define maxn 1005
struct sq
{
elep *p;
elep length;
elep size;
};
void insert(sq &l,int x)
{
l.p[l.length+1]=x;//插入元素
l.length++;//刷新表内元素个数
}
sq start()
{
sq l;
l.p=(int *)malloc(maxn*sizeof(elep));//开辟空间
l.length=0;
l.size=maxn;//设置最大容量
return l;
}
int BinarySearch(sq l ,int n, int key){ //折半查找(二分)
int low,high,mid;
low=1; //最低下标
high=n; //最高下标
while(low<=high){
mid=(low+high)/2; //二分
if(key<l.p[mid]){
high=mid-1;
}else if(key>l.p[mid]){
low=mid+1;
}else{
return mid;
}
}
return 0;
}
int main()
{
sq l;
int a,b;
l=start();
while(~scanf("%d",&a))
{
insert(l,a);
if(getchar()=='\n') {
scanf("%d",&b);
printf("%d\n",BinarySearch(l,l.length,b));
}}}