gpt4 book ai didi

c - 奇怪的冒泡排序行为

转载 作者:太空狗 更新时间:2023-10-29 15:25:10 25 4
gpt4 key购买 nike

谁能解释为什么这个冒泡排序函数不起作用以及为什么我在输出中丢失数字?我是 C 的新手,所以如果这是我错过的非常明显的事情,请原谅我。

#include <stdio.h>
#include <stdlib.h>

int bubble(int array[],int length) {
int i, j;
int temp;

for(i = 0; i < (length); ++i) {
for(j = 0; j < (length - 1); ++j) {
if(array[i] > array[i+1]) {
temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
}
}
}
return 0;
}

int main() {
int array[] = {12,234,3452,5643,0};
int i;
int length;

length = (sizeof(array)/sizeof(int));
printf("Size of array = %d\n", length);
bubble(array, length);
for (i = 0; i < (length); ++i) {
printf("%d\n", array[i]);
}
return 0;
}

输出

Size of array = 5
12
234
3452
0
0

最佳答案

在你的内部循环中,你根本不使用 j 。仔细检查你的逻辑。另请注意,array[i+1] 超出了数组边界。

关于c - 奇怪的冒泡排序行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2799361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com