最近打算研究一下基础的算法,就先从二分开始做吧,三种方法
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1024;
int num[MAXN];
//生成测试数据
void init()
{
for(int i = 0; i < MAXN; i++)
num[i] = i * 3;
}
//循环查找
int query1(int n)
{
int l = 0, r = MAXN;
while(l <= r){
int mid = (l + r) >> 1;
if(num[mid]==n) return mid;
else if(num[mid]<n) l = mid + 1;
else r = mid - 1;
}
return -1;
}
//递归查找
int query2(int l, int r, int n)
{
if(l > r) return -1;
int mid = (l + r) >> 1;
if(num[mid]==n) return mid;
else if(num[mid] < n) return query2(mid + 1, r, n);
else return query2(l, mid-1, n);
}
//STL查找
int query3(int n)
{
if(!binary_search(num, num+MAXN, n))
return -1;
return lower_bound(num, num+MAXN, n) - num;
}
void run()
{
int n;
printf("
输入要查找的数:");
cin >> n;
printf("%d 的下标为:
", n); //输出-1为不存在
cout << "循环查找:" << query1(n) << endl;
cout << "递归查找:" << query2(0, MAXN, n) << endl;
cout << "STL查找:" << query3(n) << endl;
run();
}
int main()
{
init();
run();
return 0;
}