第六章:数组07
让编程改变世界
Change the world by program
二维数组程序举例 -- 二分法举例
假设在数组a中的数据是按由小到大顺序排列的:
-12 0 6 16 23 56 80 100 110 115,从键盘上输入一个数,判定该数是否在数组中,若在,输出所在序号。TIPS:
第一步:设low、mid和high三个变量,分别指示数列中的起始元素、中间元素与最后一个元素位置, 其初始值为low=0,high=9,mid=4,判断mid指示的数是否为所求,mid指示的数是23,不是要找的80,须继续进行查找。 [caption id="attachment_109" align="aligncenter" width="361"]![二分法原理](http://blog.fishc.com/wp-content/uploads/2012/07/11.gif)
![二分法原理](http://blog.fishc.com/wp-content/uploads/2012/07/22.gif)
![二分法原理](http://blog.fishc.com/wp-content/uploads/2012/07/3.gif)
![二分法原理](http://blog.fishc.com/wp-content/uploads/2012/07/4.gif)
代码清单:
[codesyntax lang="c"]#define M 10 #include<stdio.h> void main() { static int a[M] = {-12,0,6,16,23,56,80,100,110,115}; int n, low, mid, high, found; low=0; high=M-1; found=0; printf("Input a number to be searched:"); scanf("%d", &n); //以上进行一系列预处理…… while(low <= high) { mid = (low+high)/2; if(n == a[mid]) { found = 1; break; } /*找到,结束循环*/ else if(n > a[mid]) low=mid+1; else high=mid-1; } if(found == 1) printf("The index of %d is %d",n,mid); else printf("There is not %d",n); }[/codesyntax] [buy] 获得所有教学视频、课件、源代码等资源打包 [/buy] [Downlink href='http://kuai.xunlei.com/d/LOAOVYTAAFSL']视频下载[/Downlink]