顺序表应用6:有序顺序表查询
Time Limit: 7MS Memory limit: 700K
题目描述
顺序表内按照由小到大的次序存放着n个互不相同的整数(1<=n<=20000),任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
输入
第一行输入整数n,表示顺序表的元素个数;
第二行依次输入n个各不相同的有序整数,代表表里的元素;
第三行输入整数t,代表要查询的次数;
第四行依次输入t个整数,代表每次要查询的数值。
第二行依次输入n个各不相同的有序整数,代表表里的元素;
第三行输入整数t,代表要查询的次数;
第四行依次输入t个整数,代表每次要查询的数值。
输出
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
示例输入
10 1 22 33 55 63 70 74 79 80 87 4 55 10 2 87
示例输出
4 No Found! No Found! 10
提示
来源
示例程序
- 提交
- 状态
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define LISTINCREASMENT 20000 #define LISTSIZE 20000 #define OVERFLOW -1 #define OK 1 typedef int ElemType; typedef struct { int * elem; int length; int listsize; } Sqlist; int SqInitial(Sqlist * L) { L->elem=(int *) malloc (LISTSIZE*sizeof(int)); if (! L->elem) exit(OVERFLOW); L->length=0; L->listsize=LISTSIZE; return OK; } int search(Sqlist * l,int s,int t,int key) { int low=s,high=t,mid; if(s<=t) { mid=low+(high-low)/2; if(l->elem[mid]==key) return mid; if(l->elem[mid]>key) return search(l,low,mid-1,key); else return search(l,mid+1,high,key); } return -1; } int main() { int n,t,key; scanf("%d",&n); int i; Sqlist l; SqInitial(&l); for(i=1;i<=n;i++) scanf("%d",&l.elem[i]); scanf("%d",&t); while(t--) { scanf("%d",&key); if(search(&l,1,n,key)!=-1) printf("%d\n",search(&l,1,n,key)); else printf("No Found!\n"); } return 0; }