本題要求實現二分查找算法。
函數接口定義:
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
鳴謝寧波大學 Eyre-lemon-郎俊傑 同學修正原題!
Position BinarySearch(List L,ElementType X){ int l=0;int r=L->Last; int m=L->Last/2;int coun=L->Last; while(coun--){ if(L->Data[m]==X) return m; if(L->Data[m]<X){ l=m; m=(l+r)/2+1;//大數據查找最后一個數字,這邊要進行加一操作,這個case容易出錯 continue; } if(L->Data[m]>X){ r=m; m=(l+r)/2; } } return NotFound; }