【发布时间】:2018-08-19 05:32:36
【问题描述】:
我一直在尝试让 Java 中的简单冒泡排序方法起作用,但我看不出它为什么不起作用的问题。我希望数组中的最低元素是第一个元素,最高元素是最后一个元素。在这里,我为方法提供了已排序的数组,其值为[1, 2, 3, 4]。
输出是一个数组[1, 3, 2, 4] - 所以它排序了一些东西,尽管它不应该排序。有人看到问题了吗?
import java.util.Arrays;
public class BubbleSort {
public static int [] bubblesortMethode(int sortMe[])
{
int nrOfSwaps = 0;
for (int i = 0; i < sortMe.length - 1; i++) {
for (int j = 1; j < sortMe.length; j++) {
if(sortMe[i] > sortMe[j]){
int temp = sortMe[j];
sortMe[j] = sortMe[i];
sortMe[i] = temp;
}
}
nrOfSwaps++;
}
System.out.println("Number of swaps" + " " + nrOfSwaps);
return sortMe;
}
public static void main (String[] args) {
int sortMe [] = {1,2,3,4};
System.out.println(Arrays.toString(bubblesortMethode(sortMe)));
}
}
【问题讨论】:
-
尝试使用调试器,它会详细显示发生了什么
-
使用它对数组 1 到 10 进行排序得到 [1, 9, 8, 7, 6, 5, 4, 3, 2, 10]
标签: java arrays sorting for-loop bubble-sort