标签:bsp clu 分治 pen iostream int stdout lse cst
//对于递归的折半查找,需要考虑找不到的情况。
#include<iostream> #include<cstdio> #include<stdlib.h> #define maxn 10001 using namespace std; int a[maxn],key; //折半查找法---递归二分法 int search(int s,int e) { int mid; if(e>=s) { mid=(s+e)/2; if(a[mid]==key) { cout << mid << endl; return 0; } else if(key<a[mid]) { search(s,mid-1); } else if(key>a[mid]) { search(mid+1,e); } } else { cout << -1 << endl; } return 0; } int main(void) { freopen("half.in","r",stdin); freopen("half.out","w",stdout); int n; cin >> n; for(int i=0;i<n;i++) cin >> a[i]; cin >> key; search(0,n-1); return 0; }
标签:bsp clu 分治 pen iostream int stdout lse cst
原文地址:https://www.cnblogs.com/zuimeiyujianni/p/9025848.html