【PTA】6-10 二分查找 (20分)

【PTA】6-10 二分查找 (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

裁判测试程序样例:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define MAXSIZE 10
 5 #define NotFound 0
 6 typedef int ElementType;
 7 
 8 typedef int Position;
 9 typedef struct LNode *List;
10 struct LNode {
11     ElementType Data[MAXSIZE];
12     Position Last; /* 保存线性表中最后一个元素的位置 */
13 };
14 
15 List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
16 Position BinarySearch( List L, ElementType X );
17 
18 int main()
19 {
20     List L;
21     ElementType X;
22     Position P;
23 
24     L = ReadInput();
25     scanf("%d", &X);
26     P = BinarySearch( L, X );
27     printf("%d\n", P);
28 
29     return 0;
30 }
31 
32 /* 你的代码将被嵌在这里 */

输入样例 1:

5
12 31 55 89 101
31

输出样例 1:

2

输入样例 2:

3 

26 78 233 3
1

输出样例2:

0

函数实现细节:

 1 Position BinarySearch( List L, ElementType X ){
 2     int Low=0,Mid,High=L->Last;
 3     while(Low<=High){
 4         Mid=(High+Low)/2;
 5         if(L->Data[Mid]==X){
 6             return Mid;
 7         }else if(L->Data[Mid]>X){
 8             High=Mid-1;
 9         }else{
10             Low=Mid+1;
11         }
12     }
13     return NotFound;
14 }

 

posted @ 2020-06-09 16:47  wyjgr  阅读(506)  评论(0编辑  收藏  举报