Data structure after-school exercises (Exercise 1) Exercise 1.8 binary search (20 points)

This problem required to achieve binary search algorithm.

Function interface definition:

Position BinarySearch( List L, ElementType X );

Wherein the Liststructure is defined as follows:

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

LIt is a linear incoming user table, which ElementTypeelements can be >, =, <compare incoming data and to ensure that the subject is incremented ordered. Function BinarySearchto find Xthe Dataposition, 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;
}

 

Guess you like

Origin www.cnblogs.com/littlepage/p/11616567.html