6-3 折半查找的实现 (函数题)

给一个严格递增数列,函数Search_Bin(SSTable ST, KeyType key)用来二分地查找key在数列中的位置。

函数接口定义:

Search_Bin(SSTable ST, KeyType key)

其中ST是有序表,key是查找的值

裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>

#define NOT_FOUND -1

typedef int KeyType;

typedef struct {
    KeyType key;
}SElemType;

typedef struct {
    SElemType *elem;
    int length;
}SSTable;

int Search_Bin(SSTable ST, KeyType key);

int main () {
    SSTable T;

    scanf("%d", &T.length);
    T.elem = (SElemType *) malloc ((T.length + 1) * sizeof(SElemType));

    for(int i = 1; i <= T.length; ++ i)
        scanf("%d", &T.elem[i].key);

    KeyType key;
    scanf("%d", &key);

    int pos = Search_Bin(T, key);
    if(pos == NOT_FOUND) puts("NOT FOUND");
    else printf("%d\n", pos);
    return 0;
}
/* 你的代码将被嵌在这里 */

####输入格式:
第一行输入一个数n,表示有序表的元素个数,接下来一行n个数字,依次为表内元素值。
然后输入一个要查找的值。

####输出格式:
输出这个值在表内的位置,如果没有找到,输出"NOT FOUND"。

输入样例:

4
1 2 3 4
3

输出样例:

3

也是单纯的二分查找,只不过结构体稍微套娃了一下


 C

Search_Bin(SSTable ST, KeyType key)
{
    int head=1,tail = ST.length;
    while(head<=tail){
        int mid = (head+tail)/2;
        if(ST.elem[mid].key==key) return mid;
        if(ST.elem[mid].key>key) tail = mid-1;
        else head = mid+1;
    }
    return NOT_FOUND;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三块不一样的石头

十分满意,一分打赏~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值