【问题标题】:Sorting an array of unique random numbers at insertion在插入时对唯一随机数数组进行排序
【发布时间】:2011-11-28 13:08:50
【问题描述】:

我发现一段代码可以很好地用唯一的随机数填充数组。 我现在的问题是,我想对这些数字进行排序,但不是在数组满之后而是 随着新号码的插入。因此,当每个新数字都插入到数组中时,如果找到它应该在的位置。我用于创建唯一随机数的代码如下,提前谢谢你:

    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    using namespace std;
    #define MAX 2000        // Values will be in the range (1 .. MAX) 
    static int seen[MAX];   // These are automatically initialised to zero
                            // by the compiler because they are static.
    static int randomNum[1000];

    int main (void) {
    int i;

    srand(time(NULL));   // Seed the random number generator. 

    for (i=0; i<1000; i++) 
    {
      int r;
      do 
  {
        r = rand() / (RAND_MAX / MAX + 1);
      } 
    while (seen[r]);
        seen[r] = 1;
        randomNum[i] = r + 1;
      }

      for (i=0; i<1000; i++)
        cout << randomNum[i] << endl;

  return 0;
} 

【问题讨论】:

    标签: arrays sorting random numbers


    【解决方案1】:

    您正在寻找insertion sort

    一旦你开始工作,你应该切换到binary insertion sort。如果数组很大,二进制插入排序会快得多。

    【讨论】:

      猜你喜欢
      • 2021-06-10
      • 1970-01-01
      • 2013-01-28
      • 2016-08-15
      • 1970-01-01
      • 2019-07-15
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多