簡體   English   中英

Java氣泡排序

[英]Java bubble sort

我正在嘗試創建冒泡排序,但是我的代碼有問題。 輸出是:82345679。我希望它是:23456789。

package com.company;

public class Main {

    public static void main(String[] args) {
        // write your code here

        int[] tab = {9,8,7,6,5,4,3,2};
        int[] result = {9,8,7,6,5,4,3,2};

        for (int i = 0; i < result.length; i++ ) {
            if (i < result.length - 1 ) {
                if (result[i] > result[i+1]) {
                    result = permute(result, i);
                    i = 0;
                }
            }
        }

        for (int i: result) {
            System.out.print(i);
        }

    }

    public static int[] permute (int[] tableau, int index) {
        int temp;
        temp = tableau[index];
        tableau[index] = tableau[index+1];
        tableau[index+1] = temp;
        return tableau;
    }
}

您需要兩個循環。

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

您需要有2個循環才能將每個數字與整個數組進行比較。

氣泡分選示例

public static void bubbleSort(int[] numArray) {

    int n = numArray.length;
    int temp = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {

            if (numArray[j - 1] > numArray[j]) {
                temp = numArray[j - 1];
                numArray[j - 1] = numArray[j];
                numArray[j] = temp;
            }

        }
    }
}

參考這個問題

使用BubbleSort對int數組進行排序

可以使用ONE循環完成(盡管這不是呈現冒泡排序的常用方法):

public static void main (String args[]) {

    int[] tab = {9,8,7,6,5,4,3,2};

    int i=1;                   // let's do the bubble sort again
    while (i < tab.length) {

        // loop invariant :  t[0] <= t[1] .... <= t[i-1]

        if (tab[i-1] < tab[i]) {   // bubble here
            swap(tab, i-1, i);
            if (i>1) {
                i = i-1;  // one step to the left....
            }
        } else {
            i = i +1;     // one step to the right 
        }
    }

    for (int x: tab) {
        System.out.print(x);
    }
}

static void swap(int[] t, int i, int j) {
    int x = t[i];
    t[i] = t[j];
    t[j] = x;
}

問題在於for循環中i = 0i++的組合。 每當您進入i = 0分支時,由於i++ ,最終都會從1重新開始。 導致總是在第一次迭代之后跳過8 ,將9移到末尾。

因此,要么從-1重新開始,要么使用while循環,僅在else塊中遞增。 例如:

int i = 0;
while (i < result.length - 1) {
    if (result[i] > result[i+1]) {
        permute(result, i)
        i = 0;
    } else {
        i++;
    }
}

但是,我建議不要使用單循環冒泡排序,因為算法的復雜性很難看清(它仍然是O(n^2) ,但是只有一個循環就可以給人以O(n)的印象) 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM