【问题标题】:Bubble Sort not sorting correctly - Java冒泡排序未正确排序 - Java
【发布时间】: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)));
    }
}

【问题讨论】:

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


【解决方案1】:

不需要将 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++;
    }

【讨论】:

    【解决方案2】:

    如果是(sortMe[i] &gt; sortMe[j]),你应该只在 i j,您的代码也会交换它们。

    内部循环变量j 应该从i+1 开始,以确保j 始终是> 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;
            }
        }
    }
    

    【讨论】:

    • @CodeIsland 如果这为您解决了问题,您可以通过单击帖子左侧的复选标记将其标记为答案。 (它还从未回答队列中删除了问题)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多