二分查找

題源-中國大學MOOC-陳越、何欽銘-數據結構-2019夏-01-複雜度3 二分查找 (20 分)

本題要求實現二分查找算法。

函數接口定義:

Position BinarySearch( List L, ElementType X );

其中List結構定義如下:

typedef int Position;
typedef struct LNode *List;
struct LNode {
    ElementType Data[MAXSIZE];
    Position Last; /* 保存線性表中最後一個元素的位置 */
};

L是用戶傳入的一個線性表,其中ElementType元素可以通過>、==、<進行比較,並且題目保證傳入的數據是遞增有序的。函數BinarySearch要查找XData中的位置,即數組下標(注意:元素從下標1開始存儲)。找到則返回下標,否則返回一個特殊的失敗標記NotFound

裁判測試程序樣例:

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 10
#define NotFound 0
typedef int ElementType;

typedef int Position;
typedef struct LNode *List;
struct LNode {
    ElementType Data[MAXSIZE];
    Position Last; /* 保存線性表中最後一個元素的位置 */
};

List ReadInput(); /* 裁判實現,細節不表。元素從下標1開始存儲 */
Position BinarySearch( List L, ElementType X );

int main()
{
    List L;
    ElementType X;
    Position P;

    L = ReadInput();
    scanf("%d", &X);
    P = BinarySearch( L, X );
    printf("%d\n", P);

    return 0;
}

/* 你的代碼將被嵌在這裏 */

輸入樣例1:

5
12 31 55 89 101
31

輸出樣例1:

2

輸入樣例2:

3
26 78 233
31

輸出樣例2:

0

鳴謝寧波大學 Eyre-lemon-郎俊傑 同學修正原題!

測試點如下。

Position BinarySearch( List L, ElementType X ){
	int f;
	int LowF,HighF;
	LowF = 1;
	HighF = L->Last;
	if(L->Data[HighF]==X) return HighF;
	if(L->Data[LowF]==X) return LowF;
	for(f = (HighF + LowF )/ 2; f!=HighF&&f!= LowF; ){
		if(L->Data[f]==X){
			return f;
		}
		else if(L->Data[f]>X){
			HighF = f;
			f = (f + LowF) / 2;
		}
		else if(L->Data[f]<X){
			LowF = f;
			f = (f + HighF) / 2;
		}
		
	}
	return NotFound;
}

參考了教科書後又寫了一個版本。

Position BinarySearch( List L, ElementType X ){
	int f;
	int LowF,HighF;
	LowF = 1;
	HighF = L->Last;
	f = (HighF + LowF )/ 2;
	//if(L->Data[HighF]==X) return HighF;
	//if(L->Data[LowF]==X) return LowF;
	while( HighF>=LowF ){
		if(L->Data[f]==X){
			return f;
		}
		else if(L->Data[f]>X){
			HighF = f - 1 ;
			f = (HighF + LowF) / 2;
		}
		else if(L->Data[f]<X){
			LowF = f + 1;
			f = (LowF + HighF) / 2;
		}
		
	}
	return NotFound;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章