折半查找算法

计算机科学中,折半搜索,也称二分查找算法二分搜索,是一种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半。

复杂度分析

时间复杂度折半搜索每次把搜索区域减少一半,时间复杂度为O\left( \log n  \right)。(n代表集合中元素的个数)空间复杂度 O\left(  1  \right)。虽以递归形式定义,但是尾递归,可改写为循环。

C代码如下:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 #include<ctype.h>
 5 #include<stdbool.h>
 6 
 7 
 8 #define COMPARE(x,y) (((x) < (y)) ? -1 : ((x) == (y)) ? 0 : 1)
 9 
10 /*
11 int COMPARE(int x, int y)
12 {
13     if(x < y) {
14         return -1;
15     } else if(x == y) {
16         return 0;
17     } else {
18         return 1;
19     }
20 }
21 */
22 
23 
24 /* 非递归代码 */
25 int binsearch(int list[], int searchchnumm, int left, int right)
26 {
27     int middle;
28     while(left <= right) {
29         middle = (right + left)/2;
30         switch(COMPARE(list[middle], searchchnumm)) {
31             case -1:
32                 left = middle + 1;
33                 break;
34             case 0:

35                 return middle;
36                 break;
37             case 1:
38                 right = middle -1;
39                 break;
40             default:
41                 break;
42             }
43         }
44         return -1;
45 }
46 
47 
48 
49 /* 递归代码 */
50 int binsearch(int list[], int searchchnumm, int left, int right)
51 {
52     int middle;
53     if(left <= right) {
54         middle = (left + right)/2;
55         switch(COMPARE(list[middle], searchchnumm)) {
56         case -1:
57             return binsearch(list, searchchnumm, middle + 1, right);
58             break;
59         case 0:
60             return middle;
61             break;
62         case 1:
63             return binsearch(list, searchchnumm, left, middle - 1);
64             break;
65         default:
66             break;
67         }
68     }
69     return -1;
70 }
71 
72 int main()
73 {
74     int list[] = {2,4,5,1,-3,6,8,10,55,23};
75     int searchnum = 5;
76     int length;
77     length = sizeof(list) / sizeof(int);
78     printf("%d\n",length);
79     printf("%d\n",binsearch(list,searchnum,0,length));
80     return 0;    
81 }

 

posted @ 2013-09-26 01:40  cpoint  阅读(1196)  评论(0编辑  收藏  举报
浏览次数:travelocity promotion codes