本文實例為大家分享了C語言實現順序表的順序查找和折半查找的具體代碼,供大家參考,具體內容如下
順序查找:
#include <iostream>using namespace std;int SeqSearch(int r[],int n,int k){ r[0]=k;//下標0用作哨兵存放要查詢的數 int i=n; while(r[i]!=k)//不用判斷下標i是否越界 { i--; } return i;}int main(){ int n; cout<<"請輸入數組元素個數:"<<endl; cin>>n; int a[n+1]; cout<<"請輸入數組元素:"<<endl; for(int i=1;i<=n;i++) { cin>>a[i]; } int k; cout<<"請輸入要查詢的數:"<<endl; cin>>k; for(int i=1;i<=n;i++) { cout<<a[i]<<" "; } cout<<endl; cout<<"該數在數組中的位置為:"; cout<<SeqSearch(a,n,k); return 0;}
折半查找:
#include<iostream>using namespace std;int BinSearch1(int r[],int n,int k)//非遞歸{ int low=1,high=n;//設置查找區間 while(low<=high)//如果區間存在 { int mid=(low+high)/2; if(k<r[mid])high=mid-1;//查找在左半區進行,回到while那一步 else if(k>r[mid])low=mid+1; else return mid; } return 0;//如果區間不存在,則返回0,查找失敗}int BinSearch2(int r[],int low,int high,int k)//遞歸{ int mid=(low+high)/2; if(low>high) return 0; else { if(k<r[mid])BinSearch2(r,low,mid-1,k); else if(k>r[mid])BinSearch2(r,mid+1,high,k); else return mid; }}int main(){ int n; cout<<"請輸入數組元素個數:"; cout<<endl; cin>>n; int a[n+1]; cout<<"請輸入數組元素:"; cout<<endl; for(int i=1;i<=n;i++) { cin>>a[i]; } cout<<"請輸入要查找的數:"; cout<<endl; int k; cin>>k; cout<<"該數在數組中的位置是:"<<endl; cout<<BinSearch1(a,n,k);cout<<endl; cout<<BinSearch2(a,1,n,k);}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選