标签:
假设有已经排好顺序的一组数据a[n],要找出某个数searchnum是否在其中。我们假设这组数据的左边界为left,右边界为right。
初始化时 left=0,right=n-1;得出中间位置为middle=(left+right)/2;当left<=right时, 有3种情况:
1.searchnum>a[minnle] ,这时left=middle+1,right=n-1;
2.searchnum=a[middle],此时找到该数;
3.seacrch<a[middle],这时left=0,right=middle-1;
重复以上步骤,若直到left>right,仍没有出现searchnum=a[middle],则该数据不在其中。
下面分别是迭代和递归实现。
//迭代 #include<stdio.h> int main (void) { int searchnum,right,left,a[8]={1,3,5,7,8,9,15,25},n=8,middle; scanf("%d",&searchnum); left=0; right=n-1; while(left<=right) { middle=(left+right)/2; if(a[middle]==searchnum) break; else if(a[middle]>searchnum) right=middle-1; else left=middle+1; } if(left>right) { printf("no found\n"); } else { printf("%d\n",middle); } return 0; }
//递归 #include<stdio.h> int dichotomy(int left,int right,int m,int a[]); int main (void) { int m,right,left,a[8]={1,3,5,7,8,9,15,25},n=8,middle; scanf("%d",&m); left=0; right=n-1; if(dichotomy(left,right,m,a)==-1) printf("no found\n"); else printf("%d\n",dichotomy(left,right,m,a)); return 0; } int dichotomy(int left,int right,int m,int a[]) { int middle; if(left<=right) { middle=(left+right)/2; if(m==a[middle]) { return middle; } else if(m<a[middle]) { return dichotomy(left,middle-1,m,a); } else { return dichotomy(middle+1,right,m,a); } } return -1; }
标签:
原文地址:http://www.cnblogs.com/tanxing/p/4565090.html