not260 2022-09-13 00:40 采纳率: 75%
浏览 29
已结题

编程,让用户输入一个一个账号,检验该账号是否出现在下面的列表中。如果属于下面列表中的账号,则输出合法信息,否则输出非法信息。采用线性查找方法实现该程序。


5658845  4520125  7895122  8777541  8451277  1302850  80801524568555  5552012  5050552  7825877  1250255  1005231  65452313852085  7576651  7881200  4581002
1、算法分析
先用选择排序法装饰所给的账号排序,然后采用二分查找算法检验输入账号的合法性。
2、参考代码
#include<iostream>
using namespace std;
int binarysearch(int a[],int n=10,int value=0000000);
void selectionsort(int a[],int n=10);
int main()
 {    
int test[]={5658845,4520125,7895122,8777541,8451277,1302850,8080152,4568555,5552012,5050552,7825877,1250255,1005231,6545231,3852085,7576651,7881200,4581002};
int accounts;selectionsort(test,18);
cout<<”请输入要查找的账号:”;    
cin>>accounts;    
if(binarysearch(test,sizeof(test)/sizeof(test[0]),accounts))        
cout<<”合法账号!”<<endl;    
else        
cout<<”非法账号!”<<endl;    
return 0;
}
//选择排序函数void selectionsort(int a[],int n)
//二分查找函数int binarysearch(int a[],int n,int value)
  • 写回答

1条回答 默认 最新

  • _GX_ 2022-09-13 04:33
    关注
    #include <iostream>
    
    using namespace std;
    
    void swap(int *a, int *b) {
      int t = *a;
      *a = *b;
      *b = t;
    }
    
    void selectionsort(int a[], int n) {
      for (int i = 0; i < n - 1; i++) {
        int min_idx = i;
        for (int j = i + 1; j < n; j++)
          if (a[j] < a[min_idx])
            min_idx = j;
        if (min_idx != i)
          swap(&a[min_idx], &a[i]);
      }
    }
    
    int binarysearch(int a[], int n, int value) {
      int left = 0, right = n - 1;
      while (left <= right) {
        int m = (left + right) / 2;
        if (a[m] < value)
          left = m + 1;
        else if (a[m] > value)
          right = m - 1;
        else
          return m;
      }
      return -1;
    }
    
    int main() {
      int test[] = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
                    8080152, 4568555, 5552012, 5050552, 7825877, 1250255,
                    1005231, 6545231, 3852085, 7576651, 7881200, 4581002};
      std::size_t size = sizeof(test) / sizeof(int);
      selectionsort(test, size);
      cout << "请输入要查找的账号:";
      int account;
      cin >> account;
      int index = binarysearch(test, size, account);
      if (index >= 0 && index < size)
        cout << "合法账号!" << endl;
      else
        cout << "非法账号!" << endl;
      return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月21日
  • 已采纳回答 9月13日
  • 创建了问题 9月13日

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢