java冒泡排序

來源:互聯網
上載者:User

標籤:class   bubble   col   ==   date   最大   資料   ...   標記   

/** * 冒泡排序:Java * * @author skywang * @date 2014/03/11 */public class BubbleSort {    /*     * 冒泡排序     *     * 參數說明:     *     a -- 待排序的數組     *     n -- 數組的長度     */    public static void bubbleSort1(int[] a, int n) {        int i,j;        for (i=n-1; i>0; i--) {            // 將a[0...i]中最大的資料放在末尾            for (j=0; j<i; j++) {                if (a[j] > a[j+1]) {                    // 交換a[j]和a[j+1]                    int tmp = a[j];                    a[j] = a[j+1];                    a[j+1] = tmp;                }            }        }    }    /*     * 冒泡排序(改進版)     *     * 參數說明:     *     a -- 待排序的數組     *     n -- 數組的長度     */    public static void bubbleSort2(int[] a, int n) {        int i,j;        int flag;                 // 標記        for (i=n-1; i>0; i--) {            flag = 0;            // 添加一個標記,如果一趟遍曆中發生了交換,則標記為true,否則為false。如果某一趟沒有發生交換,說明排序已經完成!            // 將a[0...i]中最大的資料放在末尾            for (j=0; j<i; j++) {                if (a[j] > a[j+1]) {                    // 交換a[j]和a[j+1]                    int tmp = a[j];                    a[j] = a[j+1];                    a[j+1] = tmp;                    flag = 1;                   }            }            if (flag==0)                break;            // 退出演算法        }    }    public static void main(String[] args) {        int i;        int[] a = {20,40,30,10,60,50};        System.out.printf("before sort:");        for (i=0; i<a.length; i++)            System.out.printf("%d ", a[i]);        System.out.printf("\n");        bubbleSort1(a, a.length);        //bubbleSort2(a, a.length);        System.out.printf("after  sort:");        for (i=0; i<a.length; i++)            System.out.printf("%d ", a[i]);        System.out.printf("\n");    }}

冒泡排序時間複雜度

冒泡排序的時間複雜度是O(N2)。
假設被排序的數列中有N個數。遍曆一趟的時間複雜度是O(N),需要遍曆多少次呢?N-1次!因此,冒泡排序的時間複雜度是O(N2)。

 

冒泡排序穩定性

冒泡排序是穩定的演算法,它滿足穩定演算法的定義。
演算法穩定性 -- 假設在數列中存在a[i]=a[j],若在排序之前,a[i]在a[j]前面;並且排序之後,a[i]仍然在a[j]前面。則這個排序演算法是穩定的!

轉載自 http://www.cnblogs.com/skywang12345/p/3596232.html

java冒泡排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.