【发布时间】: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