二分法查找(递归与非递归法)

来源:互联网 发布:网络三级分销体系 编辑:程序博客网 时间:2024/05/22 21:20

依然是某本日本教材上看到的

如果data数为n, 用二分法查找m次进行比较的情况下,查找范围小于。最终的查找范围是1的情况下,查找终了的时候有:

所以      


so 二分查找的演算cost也就是时间复杂度为O(log n)


在数列中查找0-19的数是否出现

先是非递归版的程序:

#include <stdio.h>#define FOUND 1#define NOTFOUND 0int ary[]={1,2,3,4,6,7,8,10,11,14,15,18};int n=sizeof(ary)/sizeof(int);int binsearch(int x, int n, int ary[]){    int low = 0, high = n-1, mid;    do {        mid = (low+high)/2;        if(x > ary[mid]) low = mid + 1;        else high = mid - 1;    } while(x!=ary[mid] && low <= high);    if(x==ary[mid]) return FOUND;    else return NOTFOUND;}main(){    int i;    for(i=0; i<20; i++)        if(binsearch(i,n,ary)==FOUND) printf("[%2d] exist\n", i);        else printf("[%2d] not exist\n", i);}

结果为:

[ 0] not exist[ 1] exist[ 2] exist[ 3] exist[ 4] exist[ 5] not exist[ 6] exist[ 7] exist[ 8] exist[ 9] not exist[10] exist[11] exist[12] not exist[13] not exist[14] exist[15] exist[16] not exist[17] not exist[18] exist[19] not exist

接着是递归版的程序


#include <stdio.h>#define FOUND 1#define NOTFOUND 0int ary[] = {1, 2, 3, 4, 6, 7, 9, 10, 11, 14, 15, 18};int n = sizeof(ary)/sizeof(int);int binsearch(int x, int low, int high, int ary[]){    int mid = (low + high)/2;    if(low > high) return NOTFOUND;    if(ary[mid] == x) return FOUND;    if(x > ary[mid]) return binsearch(x, mid+1, high, ary);    else return binsearch(x, low, mid-1, ary);}int main() {    int i;    for(i=0; i<20; i++)        if(binsearch(i, 0, n-1, ary)==FOUND ) printf("[%2d] exist\n", i);        else printf("[%2d] not exist\n", i);}

结果同上

0 0
原创粉丝点击