• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
会发光的大月亮
博客园    首页    新随笔    联系   管理    订阅  订阅
二分查找:查找学生信息

 

 

 

 

#include<algorithm>
#include<string.h>
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
struct Student
{
    char no[100];
    char name[100];
    int age;
    char sex[5];
    bool operator < (const Student &A) const     //重载使得能够用sort函数进行排序
    {
        return strcmp(no, A.no)<0;
    }
}buf[1000];

int main()
{
    int n;
    int m;
    while (scanf_s("%d", &n) != EOF)
    {
        for (int i = 0; i < n; i++)
        {
            std::cin >> buf[i].no >> buf[i].name >> buf[i].sex >> buf[i].age;
        }
        sort(buf, buf + n);
        std::cin >> m;
        while (m-- != 0)
        {
            int ans = -1;
            char x[30];
            std::cin >> x;  //待查找学号
            int top = n - 1, base = 0;
            while (top >= base)
            {
                int mid = (top + base) / 2;
                int tmp = strcmp(buf[mid].no, x);
                if (tmp == 0)
                {
                    ans = mid;
                    break;
                }
                else if (tmp > 0)
                    top = mid - 1;
                else
                    base = mid + 1;
            }
            if (ans == -1)
                cout << "No answer" << endl;
            else
                printf("%s %s %s %d", buf[ans].no, buf[ans].name, buf[ans].sex, buf[ans].age);
        }
    }
    return 0;
}

 

posted on 2021-03-03 18:40  会发光的大月亮  阅读(151)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3