我找到了一段代码,可以很好地填充一个带有唯一随机数的数组。 我现在的问题是,我想对这些数字进行排序,但不是在数组已满之后 正在插入新号码。因此,当每个新数字插入到数组中时,如果找到它所在的位置。我在下面创建唯一随机数的代码,请提前感谢:
#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;
}