JAVA排序算法---歸併排序

package 測試包;
import java.util.Arrays;
public class MergeSort {
    /**
     * 歸併排序
     * 簡介:將兩個(或兩個以上)有序表合併成一個新的有序表 即把待排序序列分爲若干個子序列,每個子序列是有序的。
     * 然後再把有序子序列合併爲整體有序序列
     * 時間複雜度爲O(nlogn)
     * 穩定排序方式
     * aa[]待排序數組
     * 輸出有序數組
     */
//排序
    public static int[] sort(int[] aa, int low, int high) {
        int mid = (low + high) / 2;
        if (low < high) {
            // 左邊遞歸
            sort(aa, low, mid);
            // 右邊遞歸
            sort(aa, mid + 1, high);
            // 左右歸併
            merge(aa, low, mid, high);
        }
        return aa;
    }
//歸併
    public static void merge(int[] aa, int low, int mid, int high) {
        int[] temp = new int[high - low + 1];
        int i = low;// 左指針
        int j = mid + 1;// 右指針
        int k = 0;
        // 把較小的數先移到新數組中
        while (i <= mid && j <= high) {
            if (aa[i] < aa[j]) {
                temp[k++] = aa[i++];
            } else {
                temp[k++] = aa[j++];
            }
        }
        // 把左邊剩餘的數移入數組
        while (i <= mid) {
            temp[k++] = aa[i++];
        }
        // 把右邊邊剩餘的數移入數組
        while (j <= high) {
            temp[k++] = aa[j++];
        }
        // 把新數組中的數覆蓋aa數組
        for (int k2 = 0; k2 < temp.length; k2++) {
            aa[k2 + low] = temp[k2];
        }
    }
// 歸併排序的測試
    public static void main(String[] args) {
        int[] aa = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
        MergeSort.sort(aa, 0, aa.length-1);
        System.out.println(Arrays.toString(aa));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章