数据结构与算法------二分查找
2015-12-08 16:02
741 查看
二分查找
1.算法:假设数据按升序排列,取中间位置值,如果目标等于中值,则查找成功;如果目标小于中值,则在中值左侧继续查找;如果目标大于中值,则在中值右侧继续查找;直到找到或者找不到为止。
2.评价:O(logN),数据必须有序。
测试结果:
Pls input the size:25
5 8 26 30 46 56 59 72 88 100 101 101 110 113 123 129 132 137 148 157 171 180 182 185 188
Pls input the value:100
data[9] = 100
1.算法:假设数据按升序排列,取中间位置值,如果目标等于中值,则查找成功;如果目标小于中值,则在中值左侧继续查找;如果目标大于中值,则在中值右侧继续查找;直到找到或者找不到为止。
2.评价:O(logN),数据必须有序。
#include<iostream> #include<cstdlib> using namespace std; int bfind(int *data,int size,int value){//二分查找->返回元素下标 int left=0; int right=size-1; while(left<=right){ int mid=(left+right)/2; if(data[mid]<value) left=mid+1; else if(data[mid]>value) right=mid-1; else{ return mid; } } return -1; } void bubbleSort(int *data,int size){//使用冒泡排序将随机生成的数据排序,以便二分查找 int i,j; for(int i=0;i<size-1;++i){ bool flag=true; for(int j=0;j<size-1-i;++j){ if(data[j]>data[j+1]){ int tmp=data[j]; data[j]=data[j+1]; data[j+1]=tmp; flag=false; } } if(flag==true) break; } } int main(){ int *data=new int; int size,value; cout<<"Pls input the size:"; cin>>size; srand(time(0)); for(int i=0;i<size;++i){ data[i]=rand()%200; } bubbleSort(data,size); for(int i=0;i<size;++i) cout<<data[i]<<' '; cout <<endl; cout<<"Pls input the value:"; cin>>value; int ret=bfind(data,size,value); if(ret==-1) cout << "Not found" << endl; else cout<<"data["<<ret<<"] = "<<value<<endl; return 0; }
测试结果:
Pls input the size:25
5 8 26 30 46 56 59 72 88 100 101 101 110 113 123 129 132 137 148 157 171 180 182 185 188
Pls input the value:100
data[9] = 100
相关文章推荐
- 数据结构:Binary and other trees(数据结构,算法及应用(C++叙事描述语言)文章8章)
- 数据结构-C:二叉树的遍历
- 数据结构与算法------线性查找
- 数据结构与算法-----归并排序
- Huffman树及Huffman编码(数据结构)
- 数据结构实验之查找六:顺序查找
- 数据结构C++语言描述专题系列 (四) 链式栈和队列
- 主席树学习
- 数据结构实验之查找三:树的种类统计
- 【Codeforces Round 271 (Div 2)F】【贪心 线段树】Ant colony 区间段内是其他所有数因子的数的个数
- 【Codeforces Round 271 (Div 2)E】【离散化线段树】Pillars 最长连续序列使得序列相邻的数差值至少为k
- 数据结构C++语言描述专题系列 (三) 队列
- 【Codeforces Round 271 (Div 2)B】【前缀和二分 or 暴力】Worms 每种类型多个个数第i个数什么类型
- 收藏(数据结构)
- 数据结构线性表
- 学习数据结构好的博客
- Linux C 算法与数据结构 --二叉树
- 数据结构基础之堆排序(Java 实现)
- 数据结构(C语言版)严蔚敏 实习2 停车场管理 问题
- 模版整理(数据结构)【待更新】