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


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

    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

    Output 

    4
    No Found!
    No Found!
    10
     1 #include <iostream>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 #include <stdio.h>
     5 using namespace std;
     6  
     7 int n, m;
     8 #define maxsize 10000010
     9 typedef int element;
    10 typedef struct
    11 {
    12     element * elem;
    13     int length;
    14     int listsize;
    15 }sq;
    16  
    17 int Inlist(sq & l)
    18 {
    19     l.elem = (element * )malloc(maxsize * sizeof(element));
    20     if(!l.elem)
    21         return -1;
    22     l.length = 0;
    23     l.listsize = maxsize;
    24     return 0;
    25 }
    26  
    27 void creat(sq & l)
    28 {
    29     for(int i = 0 ; i < n; i++)
    30         cin >> l.elem[i];
    31     l.length = n;
    32 }
    33  
    34 void find(sq & l, int s, int t, int key)
    35 {
    36     int low = s, high = t;
    37     if(s <= t)
    38     {
    39         int mid = low + (high - low) / 2;
    40         if(l.elem[mid] == key)
    41         {
    42             cout << mid + 1 << endl;
    43             return;
    44         }
    45         if(l.elem[mid] > key)
    46             find(l, low, mid - 1, key);
    47         else
    48             find(l, mid + 1, high, key);
    49     }
    50     if(s > t)
    51         cout << "No Found!" << endl;
    52 }
    53  
    54  
    55 int main()
    56 {
    57     ios::sync_with_stdio(false);            //加速输入输出,不然用scanf printf
    58     sq l;
    59     int t, x;
    60     cin >> n;
    61     Inlist(l);
    62     creat(l);
    63     cin >> t;
    64     while(t--)
    65     {
    66         cin >> x;
    67         find(l, 0, n - 1, x);
    68     }
    69     return 0;
    70 }
  • 相关阅读:
    Jrain'Lのvueblog
    前端知识整理 の IMWeb
    js编程小练习1
    mac版本cornerstone的无限期破解方法(转)
    教你解锁被锁住的苹果mac电脑的文件跟文件夹,同时也可删除被锁的文件跟文件夹(转)
    Mac下配置svn服务器
    ios 查看模拟器路径以及应用的文件夹
    python怎么解压压缩的字符串数据
    python全局变量被覆盖的问题
    PyInstaller:把你的Python转为Exe
  • 原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12584016.html
Copyright © 2020-2023  润新知