-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path01_3_BinarySearch.cpp
114 lines (89 loc) · 1.97 KB
/
01_3_BinarySearch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
* BinarySearch.cpp
*
* Created on: 2018年4月7日
* Author: Summer
*/
/*
* 01-复杂度3 二分查找(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要查找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(); //
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
*/
#define MAXSIZE 10
#define NotFound 0
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last;
};
Position BinarySearch( List L, ElementType X )
{
int low, mid, high;
low = 1;
high = L->Last;
while( low <= high )
{
mid = (low + high)/2;
if ( L->Data[mid] < X )
low = mid + 1;
else if( L->Data[mid] > X )
{
high = mid - 1;
}else{
return mid;
}
}
return NotFound;
}