PTA|01-複雜度3 二分查詢 (20 分)二分查詢
阿新 • • 發佈:2018-12-14
本題要求實現二分查詢演算法。
函式介面定義:
Position BinarySearch( List L, ElementType X );
其中List結構定義如下:
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 儲存線性表中最後一個元素的位置 */
};
L是使用者傳入的一個線性表,其中ElementType元素可以通過>、==、<進行比較,並且題目保證傳入的資料是遞增有序的。函式BinarySearch要查詢X在Data中的位置,即陣列下標(注意:元素從下標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
程式碼實現
Position BinarySearch( List S, ElementType K ) { int left=1; int right=S->Last; if(S==NULL) return NotFound; while (left <= right) { int mid = (left + right) / 2; if(S->Data[mid]==K) return mid; else if(S->Data[mid]>K) right=mid-1; else left=mid+1; } }