数据结构笔记#二分法查找

复习一下

 1 #include <stdio.h>
 2 
 3 struct List
 4 {
 5     int array[20];
 6     int Length;
 7 };
 8 typedef struct List LIST;
 9 
10 int BinarySearch(LIST *list,int k) {
11     int left, mid, right;
12     left = 1;
13     right = list->Length;
14     while (left <= right) {
15         mid = (left + right) / 2;
16         if (k < list->array[mid]) {
17             right = mid - 1;
18         }
19         else if (k > list->array[mid]) {
20             left = mid + 1;
21         }
22         else {
23             return mid;
24         }
25     }
26     return -1;
27 }
28 
29 int main() {
30     LIST list;
31     list.Length = 0;
32     int lop = 0, input = 0, target;
33     scanf("%d", &input);
34     while (input != 999) {
35         list.array[lop] = input;
36         lop++;
37         list.Length++;
38         scanf("%d", &input);
39     }
40     for (lop = 0; lop < list.Length; lop++) {
41         printf("%d ", list.array[lop]);
42     }
43     printf("\n");
44 
45     scanf("%d", &target);
46     printf("The Number %d found at No.%d\n", target, BinarySearch(&list, target) + 1);
47     return 0;
48 }

 

posted @ 2015-09-22 10:55  prop_jeff  阅读(297)  评论(0编辑  收藏  举报