c - C中数组排序算法中的段错误

标签 c arrays

我是编程初学者,正在学习 K.N.King 的“C 编程:一种现代方法”。现在我正在尝试进行第 9 章的编程项目 1,但我一直遇到段错误,我不确定代码有什么问题。感谢任何更正!

这些是说明:

编写一个程序,要求用户输入一系列整数(它存储在一个数组中),然后通过调用函数 selection_sort 对这些整数进行排序。当给定一个包含 n 个元素的数组时,selection_sort 必须执行以下操作:
1.搜索数组找到最大的元素,然后将其移动到数组的最后一个位置。
2.递归调用自身对数组的前n-1个元素进行排序。

这是我的代码:

#include <stdio.h>

void selection_sort(int n, int a[n]);

int main(void)
{
    int n;

    printf("Number of integers to sort: ");
    scanf("%d", &n);

    int a[n];

    printf("Enter the integers: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    selection_sort(n, a);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d", a[i]);

    return 0;
}

void selection_sort(int n, int a[n])
{
    int swap, max = a[n - 1];

    for (int i = 0; i < n; i++) {
        if (a[i] > max) {
            max = a[i];
            swap = a[n - 1];
            a[n - 1] = max;
            a[i] = swap;
        }
    }
    if (n > 1)
        selection_sort(n - 1, a);
}

编辑:将 while (n > 1) 更改为 if (n > 1),现在它可以完美运行。但为什么它不能与 while 一起使用?

最佳答案

您需要一个不调用 selection_sort 的条件。现在,您的 selection_sort 总是 调用 selection_sort,这会导致无限循环。

并且,由于您在每一步都递减 n,因此在某一时刻它变为负数,并且您开始访问 a[-1],这是错误的。

关于c - C中数组排序算法中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38545286/

相关文章:

javascript - postman :在环境变量的声明中使用请求名称

python - 在数组声明中生成值

C - 返回字符指针数组中重复次数最多/出现次数最多的字符串

C程序警告: format not a string literal and no format arguments

C源分析

arrays - 数组作为 Behat 步骤中的参数

php - 如何比较两个数组并在列中显示匹配项

在 C 中将 int 转换为空格

java - 静态数组如何存储在 Java 内存中?

c# - 使用 C# 将 CSV 文件读入数组