#include<iostream> #define Max 256using namespace std;typedef struct Keylist{int key[Max];int len;}Keylist;void creatKlist(Keylist L){int i=0;cout<<"**建立靜態表**\n";cout<<"你需要構建多少個資料,請輸入:";cin>>L.len;cout<<"\n";for(i=0;i<L.len;i++){cout<<"請輸入100以內的資料\n";cin>>L.key[i];}}Keylist sort(Keylist L){int i,t;for(i=0;i<L.len;i++){if(L.key[i]>L.key[i+1]){t=L.key[i];L.key[i+1]=L.key[i];L.key[i]=t;}}return L;}int Seqsearch(Keylist*L,int k)//順序查找 {int i;L->key[0]=k;for(i=L->len-1;L->key[i]!=k&&i>=0;i--)return i;}int Binsearch(Keylist L,int k)//折半查找 {int high=L.len,low=1,mid,flag=0;while(low<=high){mid=(low+high)/2;if(L.key[mid]<k)low=mid+1;else if(L.key[mid]>k)high=mid-1;}return flag;}int main(){Keylist L;int flag;creatKlist(L);int k,i,choice;cout<<"請輸入你想要執行的操作序號:\n";cout<<"1.順序查找\n2.折半查找\n";cin>>choice;switch(choice){case'1':cout<<"輸入查找關鍵字:";cin>>k;i=Seqsearch(&L,k);cout<<"順序查找只有一次\n";if(i!=-1)cout<<"關鍵碼的位置是第"<<i+1<<"個"<<endl;elsecout<<"關鍵碼不存在!"<<endl;break;case'2':cout<<"輸入查找關鍵字:";cin>>k;flag=Binsearch(L,k);cout<<"折半查找位置在"<<flag+1<<endl;cout<<"總共找了"<<flag+1<<"次\n";break;default:cout<<"輸入錯誤!結束行程!"<<endl;break;}return 0;}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/22459.html
標籤:基礎類
上一篇:求幫忙用C++寫一下程式
下一篇:救救孩子吧
