二分(折半)查找算法练习

二分(折半)查找算法练习
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));
    }}}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值