1:Ch8-1-1 整数序列顺序查找
查看提交统计提问
总时间限制: 10000ms 内存限制: 10000kB
描述
设计整数顺序表的顺序查找程序,并用数据测试。
要求参加查找的整数个数为10个。
输入
10个整数
输出
每个关键字及其对应的逻辑位置
样例输入
1 2 3 4 5 6 7 8 9 0
样例输出
1:1
2:2
3:3
4:4
5:5
6:6
7:7
8:8
9:9
0:10
#include<iostream>
#include<iostream>
using namespace std;
typedef int KeyType ;
typedef int ElemType;
typedef struct{
KeyType key ; //存放关键字, KeyType 为关键字类型
ElemType data ; //其他数据, ElemType 为其他数据的类型
} sqType;
int SqSearch ( sqType R[], int n , KeyType k )//顺序查找算法
{
int i =0;
while ( i < n && R [ i ]. key != k )//从表头往后找
i++;
if ( i >= n ) //未找到返回0
return 0;
else
return i+1;//找到后返回其逻辑序号 i +1
}
int main()
{
sqType R[100];
for(int i=0;i<10;i++)
{
R[i].key=i+1;
cin>>R[i].data;
}
for(int i=0;i<10;i++)
{
cout<<R[i].data<<":"<<SqSearch(R,10,R[i].key)<<endl;
}
}
2:Ch8-1-2 整数序列折半查找
查看提交统计提问
总时间限制: 10000ms 内存限制: 1024kB
描述
已知整数序列为2,4,7,9,10,14,18,26,32,40,设计整数递增有序顺序表的折半查找程序,并用相关数据进行测试。
其中第一个整数编号为1,第二个为2,依次类推。
输入
待查找的整数key
输出
整数key 整数key在整数序列中的序号 折半查找key时的查找次数
如果key在整数序列中不存在,其序号输出为0.
样例输入
2
样例输出
2 1 3
#include<iostream>
using namespace std;
typedef int KeyType ;
typedef int ElemType;
typedef struct{
KeyType key ; //存放关键字, KeyType 为关键字类型
ElemType data ; //其他数据, ElemType 为其他数据的类型
} sqType;
int cnt=0;
int BinSearch(sqType R[],int n,KeyType k)
{
int low=0,high=n-1,mid;
while(low<=high)
{
cnt++;
mid=(low+high)/2;
if(R[mid].key==k)
{
return mid+1;
}
else if(R[mid].key>k)
{
high=mid-1;
}
else{
low=mid+1;
}
}
return 0;
}
int main()
{
sqType R[100];
int a[100]={2,4,7,9,10,14,18,26,32,40};
for(int i=0;i<10;i++)
{
R[i].key=a[i];
}
int k;
cin>>k;
//cout<<k<<" "<<BinSearch(R,10,k)<<" "<<cnt<<endl;
cout<<k<<" "<<BinSearch(R,10,k)<<" ";
cout<<cnt<<endl;
return 0;
}