使用布尔值进行冒泡排序以确定数组是否已排序

2024-05-17

我有以下用于冒泡排序的代码,但它根本不排序。如果我删除布尔值那么它工作正常。我知道,由于我的 a[0] 小于所有其他元素,因此没有执行交换,任何人都可以帮助我解决这个问题。

package com.sample;

public class BubleSort {
    public static void main(String[] args) {
        int a[] = { 1, 2, 4, 5, 6, 88, 4, 2, 4, 5, 8 };
        a = sortBuble(a);
        for (int i : a) {
            System.out.println(i);
        }

    }

    private static int[] sortBuble(int[] a) {
        boolean swapped = true;
        for (int i = 0; i < a.length && swapped; i++) {
            swapped = false;
            System.out.println("number of iteration" + i);

            for (int j = i+1; j < a.length; j++) {

                if (a[i] > a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                    swapped = true;
                }
            }
        }

        return a;
    }
}

这本质上与你的相同,但是工作并且效率更高:

private static int[] bubblesort(int[] nums)
{
    boolean done = false;

    for (int i = 0;  i < nums.length && !done; i++)
    {
        done = true;

        for (int j = nums.length-1; j > i; j--)
        {
            if (nums[j] < nums[j-1])
            {
                int temp = nums[j];
                nums[j] = nums[j-1];
                nums[j-1] = temp;
                done = false;
            }
        }
    }

    return nums;
}

At the end of the ith iteration, we know that the first i elements are sorted, so we don't need to look at them anymore. We need the boolean to determine if we need to continue or not. If no swaps are made, then we are done. We can remove the boolean and it will still work, but will be less efficient.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用布尔值进行冒泡排序以确定数组是否已排序 的相关文章

随机推荐