折半查找

来源:互联网 发布:t-sql语法基础知识 编辑:程序博客网 时间:2024/04/30 12:46
# include <stdio.h>/** * 时间:2016年6月5日 10:14:44 * 内容:折半查找 */int BinSearch(int*,int,int);void Info(int*,int);int main(void){int a[10]={2,1,4,3,5,6,11,9,0,7};Info(a,10);int num=BinSearch(a,10,6);printf("Final result = %d \n",num);return 0;}/** * 折半查找 * @param  a 要查找的数组 * @param  n 数组长度 * @param  x 要查找的未知量 * @return   返回结果 */int BinSearch(int* a,int n,int x){int low,high,mid;low=0;high=n-1;while (low<=high){mid=(low+high)/2;if (x<a[mid]){high=mid-1;} else if (x>a[mid]){low=mid+1;}else return mid;}return -1;}void Info(int*a,int n){for (int i=0;i<n;i++){printf("%d ",a[i]);}printf("\n");}

0 0