1. 程式人生 > 實用技巧 >簡單排序--氣泡排序

簡單排序--氣泡排序

排序原理:

1. 比較相鄰的元素。如果前一個元素比後一個元素大,就交換這兩個元素的位置。

2. 對每一對相鄰元素做同樣的工作,從開始第一對元素到結尾的最後一對元素。最終最後位置的元素就是最大值。

排序過程:

例:{4,5,6,3,2,1}

package com.sort;
/*--------------
 *  Author:Real_Q
 *  Date:2021-01-06
 *  Time:10:01
 *  Description:氣泡排序
 * {4,5,6,3,2,1};
---------------*/
public class BubbleSort {
    //排序
    public static void bubbleSort(Comparable[] comparables) {
        //氣泡排序 小------>大

        //排序次數 i
        for (int i = comparables.length - 1; i > 0; i--) {
            //比較大小次數及交換次數 i
            for (int j = 0; j < i; j++) {
                if (Comparable(comparables[j], comparables[j + 1])) {
                    exchange(comparables, j, j +1);
                }
            }
        }
    }
    //比較大小
    public static boolean Comparable(Comparable comparable1, Comparable comparable2) {
        return comparable1.compareTo(comparable2) > 0;
    }
    //交換元素
    public static void exchange(Comparable[] comparable, int leftIndex, int rightIndex) {
        Comparable temp;
        temp = comparable[leftIndex];
        comparable[leftIndex] = comparable[rightIndex];
        comparable[rightIndex] = temp;
    }
}

測試類:

import java.util.Arrays;
import static com.sort.BubbleSort.bubbleSort;

public class TestBubble {
    public static void main(String[] args) {
        Integer[] integers = {4,6,8,7,9,2,10,1};
        bubbleSort(integers);
        System.out.println(Arrays.toString(integers));
    }
}