設計一個程式,輸出在順序表中採用折半找法查詢關鍵字的過程
阿新 • • 發佈:2019-02-05
#include"iostream" #include"algorithm" using namespace std; class list{ private: int data[20]; int length; public: list() { cout << "元素個數為:" << endl ; cin >> length ; cout << "請輸入順序表元素" << endl ; for(int i=0;i<length;i++) cin >> data[i]; } void listsort() { sort(data,data+length); for(int i=0;i<length;i++) cout << data[i] << " "; cout << endl ; } void binsearch(int key,int a) { int half; half=a/2; if(data[half]==key&&half!=0) cout << "關鍵字的編號為: " << half+1 << endl ; else if(data[half]>key&&key>data[0]) { cout << "順序表的中值比關鍵字大,繼續在0—" << half << "中查詢" << endl ; binsearch(key,half); } else if(data[half]<key&&key<data[length-1]) { cout << "順序表的中值比關鍵字小,繼續在" << half << "-" << length << "中查詢" << endl ; binsearch(key,half+length); } else cout << "關鍵字不存在" << endl ; } int getlength() { return length; } }; void main() { int key; list a; a.listsort(); cout << "請輸入關鍵字" << endl ; cin >> key ; a.binsearch(key,a.getlength()); }