顺序表应用6:有序顺序表查询

顺序表应用6:有序顺序表查询
Time Limit: 1000 ms Memory Limit: 4096 KiB
Submit Statistic Discuss
Problem Description

顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
Input

第一行输入整数n (1 <= n <= 100000),表示顺序表的元素个数;
第二行依次输入n个各不相同的有序非负整数,代表表里的元素;
第三行输入整数t (1 <= t <= 100000),代表要查询的次数;
第四行依次输入t个非负整数,代表每次要查询的数值。
保证所有输入的数都在 int 范围内。
Output

输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Sample Input

10
1 22 33 55 63 70 74 79 80 87
4
55 10 2 87
Sample Output

4
No Found!
No Found!
10
Hint

Source

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LISTSIZE 100001
#define LISTINCREASEMENT 100
typedef struct
{
   int *elem;
   int listsize;
   int length;
}S;
void Initlist(S&L)
{
    L.elem=(int*)malloc(LISTSIZE*sizeof(int));
    L.length=0;
    L.listsize=LISTSIZE;
}
void Listinsert(S&L,int i,int e)
{
    if(L.length>L.listsize)
    {
        L.elem=(int*)realloc(L.elem,(LISTINCREASEMENT+L.listsize)*sizeof(int));
        L.listsize+=LISTINCREASEMENT;
    }
    L.elem[i]=e;
    L.length++;
}
int Search(S&L,int s,int t,int e)
{
    while(s<=t)
    {
        int mid=(s+t)/2;
        if(L.elem[mid]==e)return mid+1;
        else if(L.elem[mid]<e)return Search(L,mid+1,t,e);
        else return Search(L,s,mid-1,e);
    }
    return -1;
}
int main()
{
    int n;
    scanf("%d",&n);
    S L;
    Initlist(L);
    for(int i=0;i<n;i++)
    {
        int e;
        scanf("%d",&e);
        Listinsert(L,i,e);
    }
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int e;
        scanf("%d",&e);
        int f=Search(L,0,L.length-1,e);
        if(f==-1)printf("No Found!\n");
        else printf("%d\n",f);
    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值