二分查找
来源:互联网 发布:pdf电子杂志制作软件 编辑:程序博客网 时间:2024/06/07 04:42
1.算法
二分查找是比较常见的一种查找算法,二分顾名思义,一分为二,将有序的序列(升序或者降序)
分成两部分,根据关键字的大小确定所在区间,然后继续把新区间一分为二,判断新的区间,直到找到
或者找完也没找到为止。
2.举例代码
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<algorithm>using namespace std;int array[1001];int Binary_Search(int array[],int low,int high,int key){int mid;while(low<=high){mid=(low+high)/2;if(array[mid]==key) return 1;else if(array[mid]<key) low=mid+1;else high=mid-1;}return -1;}int main(){int n,i;int key,flag;while(scanf("%d",&n)!=EOF){memset(array,0,sizeof(array));flag=0;for(i=0;i<n;i++){scanf("%d",&array[i]);}sort(array,array+n);scanf("%d",&key);flag=Binary_Search(array,0,n-1,key);if(flag<0) printf("No find\n");else printf("Yes!Find it.\n");}return 0;}
3.算法分析
当n很大 (n>50)时, ASL(平均查找长度)≈ ㏒2(n+1)-1。
0 0
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- ios 改变图片大小缩放方法
- 【ZooKeeper Notes 28】ZooKeeper典型应用场景一览
- 【ZooKeeper Notes 6】客户端对ZooKeeper的操作是不可回退的
- 【ZooKeeper Notes 3】ZooKeeper Java API 使用样例
- 让Source Insight完美支持中文注释
- 二分查找
- ZooKeeper系列文章汇总
- 【ZooKeeper Notes 2】ZooKeeper快速搭建
- LeetCode: Divide Two Integers
- JS删除数组元素的函数介绍
- 【ZooKeeper Notes 29】 修复“ZooKeeper客户端打印当前连接的服务器地址为null”的Bug问题描述
- 责任链(Chain of Responsibility)
- 【ZooKeeper Notes 30】配置管理系统ZooKeeper与Diamond有什么不一样
- hello world