冒泡排序

一.冒泡排序

1)基本思想
從無序序列頭部開始,進(jìn)行兩兩比較,根據(jù)大小交換位置,直到最后將最大(?。┑臄?shù)據(jù)元素交換到了無序隊列的隊尾,從而成為有序序列的一部分;下一次繼續(xù)這個過程,直到所有數(shù)據(jù)元素都排好序。
2)時間復(fù)雜度
平均時間復(fù)雜度為O(n^2)

public class BubbleSortTest {

    /**
     * 冒泡排序
     */
    public static int[] bubbleSort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        return a;
    }

    /**
     * 冒泡排序優(yōu)化一: 設(shè)置標(biāo)志位flag標(biāo)記一趟排序是否發(fā)生交換,如果沒有交換,則數(shù)組已排好序
     */
    public static int[] bubbleSort1(int[] a) {
        int flag = 0;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    flag = 1;
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
            if (flag == 0) {
                break;
            }
        }

        return a;
    }
    /**
     * 輸出數(shù)組
     */
    public static void printArray(int[] a) {

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }

    public static void main(String[] args) {
        int[] a = {5, 12, 45, 6, 3, 2, 123};
        a = bubbleSort2(a);
        printArray(a);
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容