这是我写的顺序查找和二分查找代码
#include<iostream.h>
#define elemtype int
int sqsearch(elemtype a[],int n,elemtype x); //顺序查找
int sqsearch2(elemtype a[],int n,elemtype x); //顺序查找,打印查找过程
int binsearch(elemtype a[],int n,elemtype x); //折半查找
int binsearch2(elemtype a[],int n,elemtype x); //折半查找,打印查找过程
void printarray(elemtype a[],int n); //打印数组数据
int main()
{
int i,x;
const int n=9;
elemtype a1[10]={0,34,23,12,56,90,78,89,45,67};
elemtype a2[10]={0,12,23,34,45,56,67,78,89,90};
//顺序查找
cout<<"顺序查找:"<<endl;
cout<<"a1[]=";
printarray(a1,n);
cout<<"输入要查找的数据:";
cin>>x;
if((i=sqsearch(a1,n,x))>0) //找到
cout<<"找到x==a1["<<i<<"]"<<endl;
else //未找到
cout<<"找不到"<<x<<endl;
cout<<endl<<"查找过程:"<<endl;
sqsearch2(a1,n,x); //查找过程
cout<<"完成顺序查找!"<<endl;
//二分法查找
cout<<"二分法查找:"<<endl;
cout<<"a2[]=";
printarray(a2,n);
cout<<"输入要查找的数据:";
cin>>x;
if((i=binsearch(a2,n,x))>0) //找到
cout<<"找到x==a1["<<i<<"]"<<endl;
else //未找到
cout<<"找不到"<<x<<endl;
cout<<endl<<"查找过程:"<<endl;
binsearch2(a2,n,x);
cout<<"完成顺序查找!"<<endl;
return 0;
}
//在数组a[1.2...n]中顺序查找x
//找到时返回元素下标,否则返回0
int sqsearch(elemtype a[],int n,elemtype x) //a[]是数组,n是元素个数,x是要查找的数
{
int i;
if(a[0]==x)
return 1;
else
{
a[0]=x;
for(i=n;!(a[i]==x);--i); //若找到则i大于0
return i;
}
}
//在数组a[1.2...n]中顺序查找x,打印每次比较结果
//找到时返回元素下标,否则返回0
int sqsearch2(elemtype a[],int n,elemtype x) //a[]是数组,n是元素个数,x是要查找的数
{
int i;
a[0]=x;
for(i=n;!(a[i]==x);--i)
if(a[i]>x)
cout<<a[i]<<">"<<x<<endl;
else
cout<<a[i]<<"<"<<x<<endl;
return i;
}
//在数组a[1.2...n]中二分法查找x
//找到时返回元素下标,否则返回0
//前提:a[1.2...n]是非递减有序的
int binsearch(elemtype a[],int n,elemtype x) //二分查找
{
int mid,low=1,high=n;
while(low<=high)
{
mid=(low+high)/2;
if(x==a[mid])
return mid;
else if(x<a[mid])
high=mid-1;
else
low=mid+1;
}
return 0;
}
//在数组a[1.2...n]中二分法查找x,每次打印比较结果
//找到时返回元素下标,否则返回0
//前提:a[1.2...n]是非递减有序的
int binsearch2(elemtype a[],int n,elemtype x) //查找过程
{
int mid,low=1,high=n;
while(low<=high)
{
mid=(low+high)/2;
if(x==a[mid])
{
cout<<a[mid]<<"="<<x<<endl;
return mid;
}
else if(x<a[mid])
{
cout<<a[mid]<<">"<<x<<endl;
high=mid-1;
}
else
{
cout<<a[mid]<<"<"<<x<<endl;
low=mid+1;
}
}
return 0;
}
//打印顺组数据a[1....n]
void printarray(int a[],int n)
{
int i;
cout<<"{";
for(i=0;i<=n;i++)
{
cout<<a[i];
while(i<n)
{
cout<<",";
break;
}
}
cout<<"}"<<endl;
}
温馨提示:答案为网友推荐,仅供参考