1. 程式人生 > >三分檢索(遞迴)

三分檢索(遞迴)

演算法實驗

#include<iostream>
#include<cstring>
#include<cmath>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<iomanip>
#include<fstream>
#include<vector>
#include<map>
using namespace std;
const int MAXN=1e4+10;
const int INF=0x3f3f3f3f
; map<int,bool> mp; int a[MAXN]; int n,pos; void gen() { int lb,ub; srand((unsigned)time(NULL)); cout<<"請輸入資料個數:"; cin>>n; cout<<"請輸入資料下限:"; cin>>lb; cout<<"請輸入資料上限:"; cin>>ub; int tmp; for(int i=1;i<=n;i++) { tmp=lb+rand()%(ub-lb+1
); if(!mp[tmp]) { a[i]=tmp; mp[tmp]=true; }else { i--; } } } int trisearch(int L,int R,int key) { if(R<L) pos=-1; else { int mid1=L+(R-L)/3; int mid2=R-(R-L)/3; if(key==a[mid1]) pos=mid1; else
if(key==a[mid2]) pos=mid2; else if(key<a[mid1]) pos=trisearch(L,mid1-1,key); else if(key>a[mid2]) pos=trisearch(mid2+1,R,key); else pos=trisearch(mid1+1,mid2-1,key); } return pos; } int main() { ios::sync_with_stdio(false); while(true) { mp.clear(); gen(); sort(a+1,a+n+1); for(int i=1;i<=n;i++) { cout<<a[i]<<" "; if(i%10==0) cout<<endl; } cout<<endl; int key; while(true) { cout<<"請輸入要查詢的數字: "; cin>>key; int ans=trisearch(1,n,key); if(ans==-1) cout<<"查詢失敗"<<endl; else cout<<"查詢成功,該數字位於排序後的第"<<ans<<"位"<<endl; cout<<endl; cout<<"是否繼續查詢另外一個數字(Y/N):"; char ch; cin>>ch; if(ch=='N') break; } } return 0; }