srand() 并生成用于算法测试的数组

srand() and generating arrays for algorithm testing

我创建了一个选择排序算法。我想用各种输入测试我的程序。

如何在不实际输入每个数组元素的情况下实现排序、反向排序和随机数组(固定长度 [即 100,000])以使用操作数组的算法进行测试?

对于随机数组,我通常使用这样的函数:

int* big_random_block_int( int size ) {
int *data = (int*)malloc( size * sizeof(int) );
int i;
for (i=0; i<size; i++)
    data[i] = rand();

return data;
}

您需要编写一些函数来为您的排序函数生成输入。像这样:

void mySort(int* a, int n) {
    // your sorting algorithm goes here.
}

// Generates some increasing sequence of numbers into a[0] .. a[n-1].
void generateSorted(int* a, int n) {
    for (int i = 0; i < n; ++i) {
        a[i] = 42 + i * i;  // for example. 
    }   
}

// Generates some decreasing sequence of numbers into a[0] .. a[n-1].
void generateSorted(int* a, int n) {
    for (int i = 0; i < n; ++i) {
        a[i] = 37 - (5 * i);
    }   
}

// Generates a random sequence of numbers into a[0] .. a[n-1],
// each number in [0, n).
void generateRandom(int* a, int n) {
    for (int i = 0; i < n; ++i) {
        a[i] = rand() % n;
    }   
}

void testSortingFunctionOnDifferentInputs() {
    int a[100];
    generateSorted(a, 100);
    mySort(a, 100);
    generateReverseSorted(a, 100);
    mySort(a, 100);
    generateRandom(a, 100);
    mySort(a, 100);
}