0
我有以下计数排序功能奇怪的输出用C
/*
*File: countingSort.c
*Description: A counting sort subroutine. Takes as input an array of integers.
* an array length and a range. All values in the input array must fall within [0, range].
* Takes O(range + arrayLen) time and O(range + arrayLen) extra space
*
*/
#include "countingSort.h"
int* countingSort(int unsorted[], int arrayLen, int range) {
int store[range + 1];
int sorted[arrayLen];
for (int i = 0; i <= range; i++) {
store[i] = 0;
}
for (int i = 0; i < arrayLen; i++) {
sorted[i] = 0;
}
for (int j = 0; j < arrayLen; j++) {
store[unsorted[j]] ++;
}
for (int i = 1; i <= range; i++) {
store[i] += store[i-1];
}
for(int j = arrayLen - 1; j >= 0; j--) {
sorted[store[unsorted[j]]] = unsorted[j];
store[unsorted[j]] --;
}
return sorted;
}
的功能是给了我很奇怪的输出。输出大部分时间都不是输入,但有时它是正常的。 这是怎么回事?
我从所谓cSortTest.c另一个文件调用它。 这个文件看起来像这样
/*
*File: cSortTest.c
*Description: Tests countingSort.c
*
*/
#include <stdio.h>
#include "countingSort.h"
int main() {
int data[8] = { 2, 1, 9, 4, 4, 56, 90, 3 };
int* p;
p = countingSort(data, 8, 90);
for (int i = 0; i < 8; i++) {
printf("%d Element: %d\n", i, *(p+i));
}
}
我应该使用数组作为页头()/释放calloc()[这里](http://www.codingunit.com/c-reference-stdlib-h-function-calloc)页面似乎暗示 –