gpt4 book ai didi

java - 为什么这个冒泡排序不能通过使用简单的静态整数数组来工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:31:35 25 4
gpt4 key购买 nike

我一直在尝试在 Java 中使用简单的静态整数数组来实现冒泡排序。不过好像有点问题。

class BubbleSort {
static int[] a = { 10, 8, 11, -6, 9 };

public void swap(int i, int k) {
if (a[i] == a[k])
return;

int temp;
temp = a[i];
a[i] = a[k];
a[k] = temp;

}

public static void main(String[] args) {
BubbleSort bs = new BubbleSort();
for (int end = a.length - 1; end > 0; end--) {
for (int i = 0; i < end; i++) {
if (a[i] > a[i + 1])
bs.swap(i, i++);
}
}
for (int j = 0; j < a.length; j++)
System.out.println(a[j]);

}
}

我期望输出 -6,8,9,10 但实际输出根本没有排序。它显示 10,8,-6,9

最佳答案

你的错误在 swap 的调用中。你的代码

bs.swap(i, i++);

等同于:

bs.swap(i, i); i=i+1;

但是你不想增加 i,当然:你想用 i 和 i+1 调用它。所以改成

bs.swap(i, i+1);

关于java - 为什么这个冒泡排序不能通过使用简单的静态整数数组来工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237236/

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