在计算机科学中,折半搜索,也称二分查找算法、二分搜索,是一种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半。
复杂度分析
时间复杂度![O\left( \log n \right)](http://upload.wikimedia.org/math/4/8/7/4875356d17c590088e90c86ccbc6a1d2.png)
![O\left( 1 \right)](http://upload.wikimedia.org/math/3/2/8/328cf57616d3e0b03f31a353819eebbf.png)
C代码如下:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
#include<stdbool.h>
#define COMPARE(x,y) (((x) < (y)) ? -1 : ((x) == (y)) ? 0 : 1)
/*
int COMPARE(int x, int y)
{
if(x < y) {
return -1;
} else if(x == y) {
return 0;
} else {
return 1;
}
}
*/
/* 非递归代码 */
int binsearch(int list[], int searchchnumm, int left, int right)
{
int middle;
while(left <= right) {
middle = (right + left)/2;
switch(COMPARE(list[middle], searchchnumm)) {
case -1:
left = middle + 1;
break;
case 0:
return middle;
break;
case 1:
right = middle -1;
break;
default:
break;
}
}
return -1;
}
/* 递归代码 */
int binsearch(int list[], int searchchnumm, int left, int right)
{
int middle;
if(left <= right) {
middle = (left + right)/2;
switch(COMPARE(list[middle], searchchnumm)) {
case -1:
return binsearch(list, searchchnumm, middle + 1, right);
break;
case 0:
return middle;
break;
case 1:
return binsearch(list, searchchnumm, left, middle - 1);
break;
default:
break;
}
}
return -1;
}
int main()
{
int list[] = {2,4,5,1,-3,6,8,10,55,23};
int searchnum = 5;
int length;
length = sizeof(list) / sizeof(int);
printf("%d\n",length);
printf("%d\n",binsearch(list,searchnum,0,length));
return 0;
}