1. 程式人生 > >6-2 折半查詢的實現 (10 分)

6-2 折半查詢的實現 (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;
}