C语言实现顺序表的顺序查找和折半查找
人气:0顺序查找:
#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); }
您可能感兴趣的文章:
加载全部内容