冒泡排序

排序算法系列之冒泡排序,所謂冒泡排序,就是將待排序的元素想象成一個個帶重量的氣泡,輕則上浮,重則下沉。

一般的,最基本的冒泡排序是要掌握的,不管是日常的開發和麪試都是需要用到的。

一、冒泡排序(BubbleSort)
1. 基本思想:
兩兩比較待排序數據元素的大小,發現兩個數據元素的次序相反時即進行交換,直到沒有反序的數據元素爲止。

  1. 排序過程:
    設想被排序的數組R[1..N]垂直豎立,將每個數據元素看作有重量的氣泡,根據輕氣泡不能在重氣泡之下的原則,從下往上掃描數組R,凡掃描到違反本原則的輕氣泡,就使其向上”漂浮”,如此反覆進行,直至最後任何兩個氣泡都是輕者在上,重者在下爲止。

    代碼都是假定排序數組已定,但是待排序的起止位置不定:

/**
* 冒泡排序:執行完一次內for循環後,最小的一個數放到了數組的最前面(跟那一個排序算法* 不一樣)。相鄰位置之間交換
*/

public class BubbleSort {   

    /**  
     * 排序算法的實現,對數組中指定的元素進行排序  
     * @param array 待排序的數組  
     * @param from 從哪裏開始排序  
     * @param end 排到哪裏  
     * @param c 比較器  
     */  
    public void bubble(Integer[] array, int from, int end) {   
        //需array.length - 1輪比較   
        for (int k = 1; k < end - from + 1; k++) {   
            //每輪循環中從最後一個元素開始向前起泡,直到i=k止,即i等於輪次止   
            for (int i = end - from; i >= k; i--) {   
                //按照一種規則(後面元素不能小於前面元素)排序   
                if ((array[i].compareTo(array[i - 1])) < 0) {   
                    //如果後面元素小於了(當然是大於還是小於要看比較器實現了)前面的元素,則前後交換   
                    swap(array, i, i - 1);   
                }   
            }   
        }   
    }   

    /**  
     * 交換數組中的兩個元素的位置  
     * @param array 待交換的數組  
     * @param i 第一個元素  
     * @param j 第二個元素  
     */  
    public void swap(Integer[] array, int i, int j) {   
        if (i != j) {//只有不是同一位置時才需交換   
            Integer tmp = array[i];   
            array[i] = array[j];   
            array[j] = tmp;   
        }   
    }   


    /**   
    * 測試   
    * @param args   
    */  
    public static void main(String[] args) {   
        Integer[] intgArr = { 7, 2, 4, 3, 12, 1, 9, 6, 8, 5, 11, 10 };   
        BubbleSort bubblesort = new BubbleSort();   
        bubblesort.bubble(intgArr,0,intgArr.length-1);
        for(Integer intObj:intgArr){
            System.out.print(intObj + " ");
        }
    }   
}  

當然冒泡排序不止一種實現方式(第二種實現):


/**
冒泡排序:執行完一次內for循環後,最大的一個數放到了數組的最後面。相鄰位置之間交換
*/
public class BubbleSort{
    //main方法
    public static void main(String[] args){
        int[] a = {2,5,6,4,7,8,9,1,3};
        BubbleSort bubble = new BubbleSort();
        bubble.bubble(a);
        for(int num:a){
            System.out.print(num + " ");
        }
    }
    //排序
    public void bubble(int[] a){
        for(int i=a.length-1;i>0;i--){
            for(int j=0;j<i;j++){
                if(new Integer(a[j]).compareTo(new Integer(a[j+1]))>0){
                    swap(a,j,j+1);
                }
            }
        }
    }
    //交換位置
    public void swap(int[] a,int x,int y){
        int temp;
        temp=a[x];
        a[x]=a[y];
        a[y]=temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章