折半查找
2015-07-19 11:34
344 查看
一、概念
折半查找(Binary Search)的查找过程是:先确定待查找记录所在的范围区间,然后逐步 缩小范围直到找到或找不到记录为止。该方法的局限性在于要排序的查找表必须有序,即
如若i<j 那么a(i)<=a(j);
二、C语言编程实现
折半查找(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; }
相关文章推荐
- Objective - C学习 (Foundation框架)-- 01结构体
- HDU 2196 Computer(求树上每个节点到其它点的最远距离)
- 使用静态IP将办公电脑用做服务器
- 一、第一个C程序
- 字符串相关
- Ubuntu1204 vim中文乱码解决方法
- 关于Eclipse无法识别手机或者模拟器的解决方案
- Handle类与线程
- C#中判断socket是否已断开的方法
- Hadoop--hbase---练习13
- javaAPI(Collection单列集合1)
- 关于双色导航栏问题
- swift2 属性
- 不是技术牛人,如何拿到国内IT巨头的Offer
- define AB_EXTERN extern "C" __attribute__((visibility ("default")))
- iOS开发 ----- vim命令合集
- [刷题]Find Minimum in Rotated Sorted Array
- Hadoop—hbase安装----练习12
- Spring的几种注入方式
- HYSBZ — 1070 修车(最小费用最大流)