c++折半查詢演算法
阿新 • • 發佈:2018-11-06
何謂折半查詢,舉個例子很快就可以明白,給你了9個數 1 2 3 4 5 6 7 8 9 讓你去找2在哪裡,這時候你肯定會說這太簡單了,但是計算機就沒那麼強了,它得拿著2和這9個數一個一個的比較,2在前面還好比較的次數比較小,但是如果讓你找6在哪呢,需要比較的次數就多了,可能你覺得多這一次兩次沒什麼差別,但是如果1到10000個數讓你找呢,這時候折半查詢的優勢就顯現出來了。我們先看2在不在1-5裡面也就是前半段,如果在前半段,我們直接不和後邊的數進行比較,我們確定2在1到5裡面之後,我們再用類似的辦法再去掉一半,看2在不在1到3面裡,如果不在我們去3到5裡找,如此下去直到找到為止,我們會發現計算機最擅長乾的事就是迭代,而優秀的演算法就是讓計算機迭代的次數少一點。c++用程式碼實現如下
#include<iostream> using namespace std; int main() { const int n=10; int i,number,top,bott,mid,loca,a[n];//mid用bott和top表示,方便迭代。 bool flag=true,sign;//設定布林變數即標誌位。 char c; cout<<"enter data:"<<endl; cin>>a[0]; i=1; while(i<n) { cin>>a[i]; if(a[i]>=a[i-1]) i++; else cout<<"enter this data again:";//輸入已經排好序的數列,也可以加上氣泡排序自動排序 } cout<<endl; for(i=0;i<n;i++) cout<<a[i]<<" "; cout<<endl; while(flag) { cout<<"input number of to look for:"; cin>>number; sign=false; top=0; bott=n-1; if((number<a[0])||(number>a[n-1])) loca=-1; while((!sign)&&(top<=bott)) { mid=(bott+top)/2; if(number==a[mid]) { loca=mid; cout<<"find"<<number<<",its position is"<<loca+1<<endl; sign=true; } else if(number<a[mid]) bott=mid-1;//捨去後一半 else top=mid+1; } if(!sign||loca==-1) cout<<number<<"has not found"<<endl; cout<<"continue or not"; cin>>c; if(c=='n'||c=='N') flag=false; } return 0; }
輸入十個已經排好序的數,然後進行查詢。