-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path6-10.c
43 lines (36 loc) · 877 Bytes
/
6-10.c
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
#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;
}
Position BinarySearch(List L, ElementType X) {
int l = 0, r = L->Last;
while (l <= r) {
int m = l + (r - l) / 2;
if (L->Data[m] == X)
return m;
else if (L->Data[m] < X)
l = m + 1;
else
r = m - 1;
}
return NotFound;
}