天天看點

資料結構與算法(冒泡排序)

/**
 * @author Ye..
 * 冒泡排序
 * 實作原理:
 * 1。比較相鄰的元素。如果前一個元素比後一個元素大,就交換這兩個元素的位置。
 * 2。對每一對相鄰元素做同樣的工作,從開始第一對元素到結尾的最後一對元素。最終最後位置的元素就是最大值。
 */
public class Bubble {

    public static void main(String[] args) {
        Integer[] attr = {4, 5, 6, 3, 2, 1};

        for (int i = attr.length - 1; i > 0; i--) {
            for (int b = 0; b < i; b++) {
                if (greater(attr[b], attr[b + 1])) {
                    exch(attr, b, b + 1);
                }
            }
        }
        System.out.println(Arrays.toString(attr));
    }


    /**
     * 比較大小
     */
    public static boolean greater(Comparable a, Comparable b) {
        return a.compareTo(b) > 0;
    }


    /**
     * 元素交換位置
     */
    public static void exch(Comparable[] c, int a, int b) {
        Comparable comparable = c[a];
        c[a] = c[b];
        c[b] = comparable;
    }
}