6-1 数据结构考题 - 顺序查找
作者 陈皓
单位 合肥师范学院
建立一个顺序表,用顺序查找的方法对其实施查找。
顺序表的类型描述:
#define MAXSIZE 50
typedef int ElemType;
typedef struct
{
ElemType *R;
int length;
} SSTable;
函数接口定义:
下面给出了 顺序查找 函数的大部分内容,但缺少了一部分(以下划线____
标识出来的部分)。
请先将以下代码中画横线的部分补充完整,然后将完整的函数Search_Seq
提交系统,完成题目要求的功能。
int Search_Seq (SSTable T,ElemType k) { int i; T.R[0]= ____ ; for ( i=____ ; T.R[ ____ ]!= k ; ____ ); return ____ ; }
该函数中的参数说明:
ElemType k
要搜索的值
顺序表中第一个数据元素存储在 T.R[1]
测试主程序样例:
int main () { SSTable T; ElemType k; Create(T); cin>>k; int pos=Search_Seq(T,k); if(pos==0) cout<<"NOT FOUND"<<endl; else cout<<pos<<endl; return 0; }
输入格式:
第一行输入一个整数n,表示顺序表的元素个数。
第二行行输入n个数字,依次为表内元素值。
第三行输入一个要查找的值。
输出格式:
输出这个值在表中的位置。如果没有找到,输出NOT FOUND。
输入样例:
5
9 5 3 7 6
7
输出样例:
4
输入样例2:
5
9 5 3 7 6
8
输出样例2:
NOT FOUND
解答:
int Search_Seq (SSTable T,ElemType k)
{
int i;
for(i=0;i<=T.length;i++)
{
if(T.R[i]==k)
{
return (i);
}
}
return 0;
}
6-2 二分查找
作者 陈越
单位 浙江大学
本题要求实现二分查找算法。
函数接口定义:
Position BinarySearch( List L, ElementType X );
其中List
结构定义如下:
typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ };
L
是用户传入的一个线性表,其中ElementType
元素可以通过>、==、<进行比较,并且题目保证传入的数据是递增有序的。函数BinarySearch
要查找X
在Data
中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记NotFound
。
裁判测试程序样例:
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 #define NotFound 0 typedef int ElementType; typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ }; List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */ Position BinarySearch( List L, ElementType X ); int main() { List L; ElementType X; Position P; L = ReadInput(); scanf("%d", &X); P = BinarySearch( L, X ); printf("%d\n", P); return 0; } /* 你的代码将被嵌在这里 */
输入样例1:
5
12 31 55 89 101
31
输出样例1:
2
输入样例2:
3
26 78 233
31
输出样例2:
0
解答:
Position BinarySearch( List L, ElementType X )
{
int low=1;
int high=L->Last;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(X>L->Data[mid])
{
low=mid+1;
}
else if(X<L->Data[mid])
{
high=mid-1;
}
else
{
return mid;
}
}
return NotFound;
}
7-1 二分查找
作者 usx程序设计类课程组
单位 绍兴文理学院
对于输入的n个整数,先进行升序排序,然后进行二分查找。
输入格式:
测试数据有多组,处理到文件尾。每组测试数据第一行输入一个整数n(1≤n≤100),第二行输入n个各不相同的待排序的整数,第三行是查询次数m(1≤m≤100),第四行输入m个待查找的整数。
输出格式:
对于每组测试,分2行输出,第一行是排序后的升序的结果,每两个数据之间留一个空格;第二行是查找的结果,若找到则输出排序后元素的位置(从1开始,每两个数据之间留一个空格),否则输出0。
输入样例:
9
4 7 2 1 8 5 9 3 6
5
10 9 8 7 -1
输出样例:
1 2 3 4 5 6 7 8 9
0 9 8 7 0
解答:
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int a[N];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
for(int i=0;i<n;i++)
{
if(i)
{
cout<<" ";
}
cout<<a[i];
}
cout<<endl;
int m,count=0;
cin>>m;
while(m--)
{
int t;
cin>>t;
int w=lower_bound(a,a+n,t)-a;
if(a[w]==t)
{
if(count==0)
{
cout<<w+1;
count=1;
}
else cout<<" "<<w+1;
}
else
{
if(count==0)
{
cout<<0;
count=1;
}
else cout<<" "<<0;
}
}
cout<<endl;
}
}