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

标签 c arrays sorting testing

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

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

最佳答案

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

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);
} 

关于c - srand() 并生成用于算法测试的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28574154/

相关文章:

java - 为什么对随机填充的数组进行排序变得越来越快

arrays - C中的String和Null终止字符数组在字面上有什么区别吗

C: free() 无效指针;无需更改地址

PHP MySQL 插入数组

java - 我在为包含整数 1-25 的数组创建循环并每行打印 5 个数字时遇到问题

c# - IQueryable 按两个或多个属性排序

c - 编译器忽略我的 else 语句

c - 如何计算C中的执行时间?

java - 如何在基于 BST 的数组中找到第 k 个最小元素? ( java )

arrays - 将哈希表转换为 O(log(k)*k + n) 中的排序数组