冒泡排序没有正确排序 - Java

时间:2018-03-10 21:25:56

标签: java arrays sorting for-loop bubble-sort

我一直试图在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)));
    }
}

2 个答案:

答案 0 :(得分:7)

如果(sortMe[i] > sortMe[j]),只有当i&lt;学家即使我&gt;您的代码也会交换它们学家

内部循环变量j应从i+1开始,以确保j始终为&gt; i

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

答案 1 :(得分:0)

没有必要将j初始化为1.初始化j为i + 1。 尝试:

for (int i = 0; i < sortMe.length - 1; i++)  {
        for (int j = i+1; j < sortMe.length; j++) {   //instead of j = 1;
            if(sortMe[i] > sortMe[j]){
                int temp  = sortMe[j];
                sortMe[j] = sortMe[i];
                sortMe[i] = temp;
            }
        }
        nrOfSwaps++;
    }