1. 程式人生 > >排序算法之歸並排序叠代實現

排序算法之歸並排序叠代實現

package 排序算法 end test 推導 歸並排序 ati int start arr

快要過節了,目前先把代碼貼上,後續加上圖示和復雜度信息

package com.jdk8.event.SortTest;

public class MergeSortIterate {
    public static void main(String[] args){
        int[] arrs = {2,7,15,30,28,5,43,66,52,86,79};
        System.out.println("歸並排序前:");
        display(arrs);
        mergeSort(arrs);
        System.out.println("歸並排序後:");
        display(arrs);
    }

    public static void mergeSort(int[] arrs) {
        int[] temp = new int[arrs.length];//臨時空間,用於存放歸並結果
        int squa = 1;//子序列起始長度為1
        while(squa < arrs.length){
            mergeDownToUp(arrs,temp,squa,arrs.length);
            squa = 2 * squa;
        }
    }

    public static void mergeDownToUp(int[] arrs, int[] temp, int squa, int length) {
        int left = 0,middle,right;

        while (left < length -2*squa + 1){//即right<length  length-right = length-2*squa+1 > left
            right = left + 2*squa -1;
            middle = (left + right)/2;
            merge(arrs,temp,left,middle,right);
            left = left + 2*squa;
        }

        //處理剩下的尾數
        if(left < length - squa + 1){ //即middle<length 推導(length -middle = length - squa + 1 > left)
            merge(arrs,temp,left,left+squa-1,length-1);
        }else{
            while(left < length){
                if(temp[left] != arrs[left]){
                    temp[left] = arrs[left];
                }
                left = left + 1;
            }
        }
    }

    public static void merge(int[] arrs, int[] temp, int start, int middle, int end) {
        int i = start,t = start,j = middle + 1;
        while (i <= middle && j<=end){
            if(arrs[i] <= arrs[j]){
                temp[t] = arrs[i];
                t = t + 1;
                i = i + 1;
            }else{
                temp[t] = arrs[j];
                t = t + 1;
                j = j + 1;
            }
        }

        while (i <= middle){//將剩余的復制到temp
            temp[t] = arrs[i];
            t = t + 1;
            i = i + 1;
        }

        while (j <= end){//將剩余的復制到temp
            temp[t] = arrs[j];
            t = t + 1;
            j = j + 1;
        }
        while (start <= end){//將temp的數據覆蓋arrs的數據
            if (arrs[start] != temp[start]){
                arrs[start] = temp[start];
            }
            start = start + 1;
        }
    }

    public static void display(int[] arrs){
        for(int i = 0;i < arrs.length;i++){
            System.out.print(" " + arrs[i] + " ");
        }
        System.out.println();
    }
}

運行結果如下:

歸並排序前:
 2  7  15  30  28  5  43  66  52  86  79 
歸並排序後:
 2  5  7  15  28  30  43  52  66  79  86 

排序算法之歸並排序叠代實現