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

    xiaoxiao2023-03-24  1

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

    Time Limit: 7MS  Memory Limit: 700KB

    Problem Description

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

    Input

     第一行输入整数n,表示顺序表的元素个数; 第二行依次输入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

    Code realization

    #include <stdio.h> #include <stdlib.h> typedef int elemtype; typedef struct { elemtype *elem; int listsize; int length; }Lis; void creat(Lis &L,int len) { L.elem = (elemtype*)malloc(len*sizeof(elemtype)); L.length = len; } void sca(Lis &L) { for(int i=0;i<L.length;i++) scanf("%d",&L.elem[i]); } //二分查找 int search(Lis &L,int s,int t,int key) { int l = s,h = t,mid; if(s<=t) { mid = l + (h - l) / 2; if(L.elem[mid]==key) { return mid; } if(L.elem[mid]>key) return search(L,l,mid-1,key); else return search(L,mid+1,h,key); } return -1; } int main() { Lis L; int n,t,m; scanf("%d",&n); creat(L,n); sca(L); scanf("%d",&t); while(t--) { scanf("%d",&m); int j = search(L,0,n-1,m); if(j==-1) <span style="white-space:pre"> </span>printf("No Found!\n"); else <span style="white-space:pre"> </span>printf("%d\n",j+1); } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1200068.html
    最新回复(0)