二分查找离左边元素最近的(可以等于)
2016-03-27 21:07
423 查看
int compare(const void *a,const void *b) { return *(int *)a-*(int *)b; } //二分查找离元素(可以等于) int bi_search(int num[10], int len, int target) { <span style="white-space:pre"> </span>int begin = 0; <span style="white-space:pre"> </span>int end = len-1;<span style="white-space:pre"> </span> <span style="white-space:pre"> </span>while(begin<end) <span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>int mid = (begin+end)/2; <span style="white-space:pre"> </span>cout<<mid<<" "<<target<<endl; <span style="white-space:pre"> </span>cout<<mid<<" "<<len-1<<endl; <span style="white-space:pre"> </span>//最近的一个 <span style="white-space:pre"> </span>if(num[mid]==target) <span style="white-space:pre"> </span>return mid; <span style="white-space:pre"> </span>else if(num[mid]>target) <span style="white-space:pre"> </span>end = mid-1; <span style="white-space:pre"> </span>else <span style="white-space:pre"> </span>begin = mid+1; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>cout<<"begin:"<<begin<<"end:"<<end<<endl; <span style="white-space:pre"> </span>return end; } void main() { int num[10]={11,35,65,25,79,54,34,66,92,30}; qsort(num,10,sizeof(int),compare); for(int i=0;i<10;i++) cout<<num[i]<<" "; cout<<endl; int index = bi_search(num, 10, 36); cout<<index<<endl; }
相关文章推荐
- linux权限之su和sudo的区别
- 99.挖地雷(未结题)
- JS异步阻塞的迷思
- [android] 利用广播实现ip拨号
- 一感冒就得红眼病,而且很严重怎么办
- 内核分析-第五周
- 详解事件和委托
- css 动画圆环
- Activiti系列(三)——设置监听器指定Assignee
- 【三层】——C#与VB.NET各显神通
- jquery EasyUi 登录页设计
- Bzoj 3110: [Zjoi2013]K大数查询 树套树
- 深度学习文档 DeepLearning 0.1 documentation
- c#DataGridView数据绑定示例——格式化单元格的内容(转)
- RAID基础及软RAID实现方式
- JVM——JVM调优工具
- 判断身份证:要么是15位,要么是18位,最后一位可以为字母,并写程序提出其中的年月日
- Linux内核协议栈(7)listen函数分析
- 筛法求素数
- uva 11246 - K-Multiple Free set(数论)