标签:style blog color io 使用 ar strong for 文件
要求:
数据必须采用顺序存储结构,必须按关键字大小有序排列。
下面举一例子:
# include <stdio.h> bin_search(int A[], int n, int key) { int low, high, mid; low = 0; high = n-1; while(low <= high) { mid = (low + high) / 2; if(A[mid] == key) return mid; //查找成功,返回mid if(A[mid] < key) low = mid + 1; //在后半序列中查找 if(A[mid] > key) high = mid - 1; //在前半序列中查找 } return -1; //查找失败,返回-1 } int main(void) { int A[10] = {2, 3, 5, 7, 8, 10, 12, 15, 19, 21}; int i, n, addr; printf("The contents of the Array A[10] are\n"); for(i=0; i<10; i++) printf("%d ", A[i]); //显示数组A中的内容 scanf("%d", &n); //输入待查找的元素 addr = bin_search(A, 10, n);//折半查找,返回该元素在数组中的下标 if(-1 != addr) printf("%d is at the %dth unit is array A\n", n, addr); else printf("There is no %d in array A\n", n);//查找失败 return 0; }
在C-Free 5.0中的输出结果是:
# include "stdio.h" int binarysearch(int a[], int length, int key) { int low = 0; int high = length-1; int mid = (low + high) / 2; while(high >= low) //循环终结条件 { if(a[mid] == key) return mid; if(key > a[mid]) //与程序清单不同,这里使用if-else来减少循环比较的次数。 { low = mid + 1; mid = (low + high) / 2; continue; //与程序清单不同,因为mid的值可能在这里被改变,因此需要continue } else(key < a[mid]) { high = mid - 1; mid = (low + high)/ 2; continue; } } return -1;} int main(void) { int a[10] = {2, 3, 5, 7, 8, 10, 12, 15, 19, 21}; int n; scanf("%d", &n); int value = binarysearch(a, 10, n); if(value == -1) printf("ERROR, the element what you want to search is not found!\n"); else printf("the index of the element is %d\n", value); return 0; }
在C-Free 5.0中的输出结果是:
12
//二分查找V0.1 实现版 //copyright@2011 July //随时欢迎读者找bug,email:zhoulei0907@yahoo.cn。 //首先要把握下面几个要点: //right=n-1 => while(left <= right) => right=middle-1; //right=n => while(left < right) => right=middle; //middle 的计算不能写在while 循环外,否则无法得到更新。 int binary_search(int array[],int n,int value) { int left=0; int right=n-1; //如果这里是int right = n 的话,那么下面有两处地方需要修改,以保证一一对应: //1、下面循环的条件则是while(left < right) //2、循环内当array[middle]>value 的时候,right = mid while (left<=right) //循环条件,适时而变 { int middle=left + ((right-left)>>1); //防止溢出,移位也更高效。同时,每次循环都需要更新。 if (array[middle]>value) { right =middle-1; //right 赋值,适时而变 } else if(array[middle]<value) { left=middle+1; } else return middle; //可能会有读者认为刚开始时就要判断相等,但毕竟数组中不相等的情况更多,如果每次循环都判断一下是否相等,将耗费时间 } return -1; }
一点补充:
标签:style blog color io 使用 ar strong for 文件
原文地址:http://www.cnblogs.com/xpjiang/p/3979784.html