This problem required to achieve binary search algorithm.
Function interface definition:
Position BinarySearch( List L, ElementType X );
Wherein the List
structure is defined as follows:
typedef int Position;
typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ };
L
It is a linear incoming user table, which ElementType
elements can be >, =, <compare incoming data and to ensure that the subject is incremented ordered. Function BinarySearch
to find X
the Data
position, i.e., the array subscripts (Note: the elements from the start storage subscript 1). Find subscript is returned, otherwise a special mark of failure NotFound
.
Referee test program Example:
#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; } /* 你的代码将被嵌在这里 */
Sample Input 1:
5
12 31 55 89 101
31
Output Sample 1:
2
Sample Input 2:
3
26 78 233
31
Output Sample 2:
0
Acknowledgments Ningbo University Eyre-lemon- Lang Junjie students revise the original title!
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 & lt) / 2 + . 1 ; // big data to find the last number, add an operation to be performed here, the error-prone case Continue ; } if(L->Data[m]>X){ r=m; m=(l+r)/2; } } return NotFound; }