BubbleSort 算法返回不需要的结果

BubbleSort Algorithm Returning Undesired Results

这是我对冒泡排序算法的实现。

 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 = 1; j < unsorted.length-1; j++) {

你不想从第一个元素开始循环,你想从 i 之后的第一个元素开始循环:

for (j = i+1; j < unsorted.length-1; j++) {

你也需要一路走到最后:

for (j = i+1; j < unsorted.length; j++) {
here is the correct code

> 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-1; i++) {
            for (j = i+1; j < unsorted.length; j++) {
                if (unsorted[i] > unsorted[j]) {
                    temp = unsorted[i];
                    unsorted[i] = unsorted[j];
                   unsorted[j] = temp;
                 }
             }
        }
   }
 }

the second loop begins after i so j alway start at i+1 and end at unsorted.length while i end at unsorted.length-1

我在电脑里保存了冒泡排序算法,是这样的(没有复制到新数组):

public static void bubbleSort (int[] v) {
      for (int i=0; i<v.length-1; i++)
         for (int j=v.length-1; j>i; j--)
            if (v[j-1]>v[j]) {
               int aux = v[j-1];
               v[j-1] = v[j];
               v[j] = aux;   
            }
   }

几件事 1)你可以在循环范围内声明 i 和 j 2)尝试在两次迭代中保持一致 0 -> length 3) less then sign in i < unsorted.length 将确保您不会超过索引范围。因为数组索引的范围从 0 到 length-1。 4)你的交换逻辑很棒,唯一需要注意的是循环范围。 5) unsorted[i] < unsorted[j] 将决定顺序的走向。

public static void bubbleSort(int[] unsorted) {
    for (int i = 0; i < unsorted.length; i++) {
        for (int j = 0; j < unsorted.length; j++) {
            if (unsorted[i] < unsorted[j]) {
                int temp = unsorted[i];
                unsorted[i] = unsorted[j];
                unsorted[j] = temp;
            }
        }
    }
}