运行冒泡排序后运行时错误

时间:2017-08-21 07:58:58

标签: c arrays runtime-error bubble-sort

我正在尝试编写一个泡泡对数组进行排序的程序,但每次运行时都会弹出此错误:runtime error: index 4 out of bounds for type 'int [e]'

这里有什么问题?

int main(void) {
    printf("How many elements are there in the array?: ");
    int e = get_int();

    int array[e];

    for (int i = 0; i < e; i++) {
        printf("Insert element #%i: ", i + 1);
        array[i] = get_int();
    }

    for (int i = 0; i < e - 1; e++) {
        for (int j = 0; j < e - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                int swap = array[j];
                array[j] = array[j + 1];
                array[j + 1] = swap;
            }
        }
    }
    printf("\n");
}

2 个答案:

答案 0 :(得分:2)

您错误输入了for循环增量部分:for (int i = 0; i < e - 1; e++)应该是:

for (int i = 0; i < e - 1; i++)

以下是更正后的版本:

#include <stdio.h>

int main(void) {
    printf("How many elements are there in the array?: ");
    int e = get_int();

    for (int i = 0; i < e; i++) {
        printf("Insert element #%i: ", i + 1);
        array[i] = get_int();
    }

    for (int i = 0; i < e - 1; i++) {
        for (int j = 0; j < e - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                int swap = array[j];
                array[j] = array[j + 1];
                array[j + 1] = swap;
            }
        }
    }
    printf("{ ");
    for (int i = 0; i < e; i++) {
        printf("%d, ", array[i]);
    }
    printf("}\n");
    return 0;
}

答案 1 :(得分:2)

除了chqrlie指出的错误之外,不要过度复杂化冒泡排序(而且它有问题,它只考虑连续的索引)。简单地写一下(注意内循环已经过优化,以避免两次处理“下三角”项目):

for (int i = 0; i < e; i++) {
    for (int j = i+1; j < e; j++) {
        if (array[j] > array[i]) {
            int swap = array[j];
            array[j] = array[i];
            array[i] = swap;
        }
    }
}