我创建了一个选择排序算法。我想用各种输入来测试我的程序。
在不实际输入每个数组元素的情况下,如何使用操作数组的算法实现排序、反向排序和随机数组(固定长度[即 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/