您的位置:首页 > 其它

折半查找

2015-07-19 11:34 344 查看
一、概念
折半查找(Binary Search)的查找过程是:先确定待查找记录所在的范围区间,然后逐步 缩小范围直到找到或找不到记录为止。该方法的局限性在于要排序的查找表必须有序,即
如若i<j 那么a(i)<=a(j);
二、C语言编程实现

//
//  main.c
//  BinarySearchDemo
//
//  Created by zhanggui on 15/7/19.
//  Copyright (c) 2015年 zhanggui. All rights reserved.
//

#include <stdio.h>
#include <time.h>
#define N 20
int BinarySearch(int a[], int n,int found)
{
int low = 0;
int high = n-1;
int mid;
//    time_t startTime,endTime;   //用于计算运行时间
//    startTime = clock();
while (low <= high) {
mid = (low+high)/2;
if (found==a[mid]) {
printf("-------------------\n");
//            endTime = clock();
//            double Total_Waste_Time = (double)(endTime-startTime)/CLOCKS_PER_SEC;
//            printf("花费时间为:%f",Total_Waste_Time);
return mid;
}else if (found<a[mid])
{
high = mid - 1;
}else {
low = mid+1;
}
}
//    endTime = clock();
//    double Total_Waste_Time = (double)(endTime-startTime)/CLOCKS_PER_SEC;
//    printf("花费时间为:%f",Total_Waste_Time);
return -1;

}

int main(int argc, const char * argv[]) {
int found;
int a
= {3,4,5,6,7,8,9,10,14,15,18,20,31,43,56,67,84,90,92,96};
printf("请输入一个数:");
scanf("%d",&found);
int i = BinarySearch(a, N, found);
if (i != -1) {
printf("在数组中的位置是%d\n",i);
}else
{
printf("没有找到");
}
return 0;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: