0

我需要对一个包含 5 个数字的数组进行排序,这就是我所拥有的。我提示输入,然后使用冒泡排序对日期进行排序,然后打印数组。但是,当我运行程序时,输出没有排序,甚至与输入不同。

void main() {
    printf("Please enter five integers:\n");
    printf("First Number\n");
    scanf("%d", &numArray[0]);
    printf("Second Number\n");
    scanf("%d", &numArray[1]);
    printf("Third Number\n");
    scanf("%d", &numArray[2]);
    printf("Fourth Number\n");
    scanf("%d", &numArray[3]);
    printf("Fifth Number\n");
    scanf("%d", &numArray[4]);

    for (j=0; j<=5; ++j) {
        if (numArray[j] > numArray[j+1]) {
            temp = numArray[j];
            numArray[j] = numArray[j+1];
            numArray[j+1] = temp;
        }
    }

    for(int j = 0; j < 5; j++) {
        printf("%d ", numArray[j]);
    }
}
4

1 回答 1

6

您的循环无效(它结束了一个),并且您的排序仅包含一个循环;冒泡排序包含两个循环:

for (i = 0; i < SIZE-1; i++) {
    for (j = i+1; j < SIZE; j++) {
        if (val[i] > val[j]) swap(...);
    }
}
于 2012-09-04T20:51:08.680 回答