折半查找
来源:互联网 发布:支付宝自动发货源码 编辑:程序博客网 时间:2024/06/03 09:03
折半查找也叫二分查找,是很快的查找方式,使用普遍,前提是数据先进行排序,比如以下例子中用到的数组就是拍好序的int arr[]={1,2,3,4,5,6,7,8,9,10};
#include <iostream>
using namespace std;int binSearch(int x,int a[],int n);
void main()
{
int arr[]={1,2,3,4,5,6,7,8,9,10};
int num;
num=9;
int result;
result=binSearch(num,arr,10);
if(result>=0)
{
printf("在arr[%d]中找到%d\n",result,num);
cout<<"在arr["<<result<<"]中找到"<<num<<endl;//c++输出格式
}
}
int binSearch(int x,int a[],int n)
{
int low ,high,mid;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;if(x<a[mid]){high=mid-1;}else if(x>a[mid]){low=mid+1;}elsereturn mid;
}}
return -1;
0 0
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 折半查找
- 常见对象_字符串的遍历
- kali切换桌面环境
- imsi和手机号码的关系
- 使用UART串口下调试CH376芯片
- linux中的数据校验方法
- 折半查找
- 3436: 小K的农场
- iOS的Cell自适应的几种解决方案
- Linux运维班第八,九单元笔记整理
- java内部私有类
- 解析Android Studio 2.2 Native新特性
- leetcode_371
- 常见对象_统计大写,小写及数字字符的个数案例
- (一)C语言基础(基本数据类型,输入输出)