顺序查找 - waiting...'s Blog

顺序查找

waiting... posted @ 2009年3月02日 23:58 in C/C++ with tags 顺序 查找 , 1401 阅读

 

  1. #include <iostream>
  2. #include <ctime>
  3. #include <cstdlib>
  4. using namespace std;
  5.  
  6. // 设置随机整数的种子
  7. void rand_seed()
  8. {
  9.         unsigned int seed = static_cast<unsigned int>(time(0));
  10.         srand(seed);
  11. }
  12.  
  13. // 返回一个介于lower与upper之间的一个随机整数
  14. int randInt(int lower, int upper)
  15. {
  16.         return lower + rand() % (upper - lower + 1);
  17. }
  18.  
  19. void print(const int a[], const int length)
  20. {
  21.         for (int i = 0; i < length; i++)
  22.                 cout << a[i] << " ";
  23.         cout << endl;
  24. }
  25.  
  26. // 如果待查找数字存在于数组中,则返回其下标;否则返回-1
  27. int linear_search(const int a[], const int length, int num)
  28. {
  29.         for (int i = 0; i < length; i++)
  30.         {
  31.                 if (a[i] == num)
  32.                         return i;
  33.         }
  34.         return -1;
  35. }
  36.  
  37. int main()
  38. {
  39.         const int length = 20;
  40.         const int lower = 1// 随机数上限
  41.         const int upper = 1000// 随机数下限
  42.         int a[length];
  43.         int num;  //  待查找的数字
  44.  
  45.         for (int i = 0; i < length; i++)
  46.                 a[i] = randInt(lower, upper);
  47.  
  48.         print(a, length);
  49.  
  50.         cout << "请输入要查找的数字:";
  51.         while (cin >> num)
  52.         {
  53.                 int num_index = linear_search(a, length, num);
  54.                 if (num_index != -1)
  55.                         cout << "a[" << num_index << "] = " << a[num_index] << endl;
  56.                 else
  57.                         cout << "未找到" << endl;
  58.                 cout << "请输入要查找的数字:";
  59.         }
  60.  
  61.         return 0;
  62. }

 

 

Avatar_small
net worth 说:
2023年12月20日 16:12

Checking out the information of any celebrity on idol net worth to know how much their name and fame worth and their family members.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee