【问题标题】:Unable to count sort more than eight elements无法计算排序超过八个元素
【发布时间】:2021-12-19 00:30:11
【问题描述】:

这是我的代码。在选择值时,如果我尝试输入 9 个值,它会转储垃圾值。在进行快速排序时也发生了这种情况

#include <stdio.h>
 
void printArray(int* A, int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", A[i]);
    }
    printf("\n");
}

int maximum(int A[],int n) {
    int i, max = A[0];
    for (i = 1; i < n; i++) {
        if (A[i] > max) {
            max = A[i];
        }
    }
    return max;
}

void countSort(int A[], int n) {  
    int i, max = maximum(A, n);
    int count[max + 1], B[n];

    for (i = 0; i < max + 1; i++) {
        count[i] = 0;
    }

    for (i = 0; i < max + 1; i++) {
        count[A[i]]++;
    }

    for (i = 1; i < n; i++) {
        count[i] += count[i - 1];
    }

    for (i = n - 1; i >= 0; i--) {
        B[--count[A[i]]] = A[i];
    }

    for (i = 0; i < n; i++) {
        A[i] = B[i];
    }
}
 
int main(){
    int A[] = {1, 4, 6, 2, 3, 2, 3, 2, 7};
    int n = 9;
    printArray(A, n); // Printing the array before sorting
    countSort(A, n);  // Function to sort the array
    printArray(A, n); // Printing the array before sorting

    return 0;
}

【问题讨论】:

  • 所以继续调试它。在调试器中运行您的程序和/或添加调试打印语句以跟踪程序执行和变量值。 How to debug small programs
  • for(i=0;i&lt;max+1;i++) count[A[i]]++; 结束索引错误。应该是 n 而不是 max+1。应该能够通过基本调试自己找到。
  • 您应该通过在countSort 中的每个循环之后打印相关数组的内容来调试此程序,以查看循环是否完成了您的预期,或者通过在调试器中查看数组,在每个循环之后环形。至少,这会准确地揭示程序中哪里出了问题。不要通过发布到 Stack Overflow 进行调试。

标签: c algorithm sorting


【解决方案1】:

此代码使用了错误的限制:

    for(i=0;i<max+1;i++) {
        count[A[i]]++;
    }

它有效地遍历 A 的元素,其中有 n 元素,而不是 max+1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2016-05-22
    • 1970-01-01
    相关资源
    最近更新 更多