顺序表应用6:有序顺序表查询
Time Limit: 7MS
Memory Limit: 700KB
Problem Description
顺序表内按照由小到大的次序存放着n个互不相同的整数(1<=n<=20000),任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
Input
第一行输入整数n,表示顺序表的元素个数;
第二行依次输入n个各不相同的有序整数,代表表里的元素;
第三行输入整数t,代表要查询的次数;
第四行依次输入t个整数,代表每次要查询的数值。
第二行依次输入n个各不相同的有序整数,代表表里的元素;
第三行输入整数t,代表要查询的次数;
第四行依次输入t个整数,代表每次要查询的数值。
Output
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Example Input
10 1 22 33 55 63 70 74 79 80 87 4 55 10 2 87
Example Output
4 No Found! No Found! 10
Hint
Author
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int *elem,listsize, length;
};
#include<stdlib.h>
#include<string.h>
struct node
{
int *elem,listsize, length;
};
struct node creat(struct node l)
{
l.elem=(int *)malloc(20000*sizeof(int ));
if(!l.elem) return l;
l.length=0;
l.listsize=20000;
return l;
};
struct node jianli_list(struct node l,int n)
{
int i;
for(i=1; i<=n; i++)
{
scanf("%d",&l.elem[i]);
}
l.length=n;
return l;
};
{
int i;
for(i=1; i<=n; i++)
{
scanf("%d",&l.elem[i]);
}
l.length=n;
return l;
};
int find_k(struct node l,int k,int n) ///二分查找(折半查找)
{
int low =1,high=n,mid=0;
while(low<=high) ///这里不要忘记等于
{
mid=(low+high)/2;
if(l.elem[mid]<k)
low=mid+1;
else if(l.elem[mid]>k)
high=mid-1; ///相等说明即是
else if(l.elem[mid]==k) return mid;
}
return 0;
}
int main()
{
struct node l;
int n,k,t;
scanf("%d",&n);
l=creat(l);
l=jianli_list(l,n);
scanf("%d",&k);
while(k--)
{
scanf("%d",&t);
t=find_k(l,t,n);
if(!t)
printf("No Found!\n");
else
printf("%d\n",t);
}
return 0;
}