【发布时间】:2017-05-21 13:35:51
【问题描述】:
这是我对冒泡排序算法的实现。
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] unsorted = {1,3,5,6,2};
System.out.println(Arrays.toString(unsorted));
bubbleSort(unsorted);
System.out.println(Arrays.toString(unsorted));
}
public static void bubbleSort(int[] unsorted){
int i;
int j;
int temp;
for (i = 0; i < unsorted.length; i++) {
for (j = 1; j < unsorted.length-1; j++) {
if (unsorted[i] > unsorted[j]) {
temp = unsorted[i];
unsorted[i] = unsorted[j];
unsorted[j] = temp;
}
}
}
}
}
这是输出:
[1, 3, 5, 6, 2]
[1, 6, 5, 3, 2]
这显然是错误的,但我的逻辑似乎没问题。
【问题讨论】:
-
你的第二个循环应该开始
for (j = i+1; ... -
这样做会输出相同的未排序数组 [1, 3, 5, 6, 2] [1, 3, 5, 6, 2]
-
去掉同一行的-1
-
第二个循环中的停止条件应该从:
j < unsorted.length-1改为:j < unsorted.length -
好吧,这行得通....现在我需要了解为什么行得通
标签: java bubble-sort