1-3 折半查找的实现 (10 分)

给一个严格递增数列,函数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
int Search_Bin(SSTable ST, KeyType key) {
  int mid=0,a=1,b=ST.length; while(a<=b) {
    mid=(a+b)/2;
    if(ST.elem[mid].key==key){
    return mid;
    }
    if(ST.elem[mid].key>key) {
    b=mid-1;
      
    }
    if(ST.elem[mid].key<key){
    a=mid+1;
    }
  }
    return -1;
}

猜你喜欢

转载自blog.csdn.net/qq_41840843/article/details/84959819