歸併排序

package org.example.sort;

import java.util.Arrays;

/**
 * @author xianzhe.ma
 * @date 2021/8/9
 */

public class Mergesort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] a = new int[]{11, 9, 7, 5, 3, 1, 12, 10, 8, 6, 4, 2};


        int[] tmp = new int[a.length];
        mergeSort(a, 0, a.length - 1, tmp);
    }

    private static void merge(int[] array, int start, int middle, int end, int[] tmp) {

        int first = start;
        int second = middle + 1;
        int index = start;


        while ((first <= middle) && (second <= end)) {
            if (array[first] >= array[second])
                tmp[index++] = array[second++];
            else
                tmp[index++] = array[first++];
        }
        while (first <= middle)
            tmp[index++] = array[first++];
        while (second <= end)
            tmp[index++] = array[second++];

        for (first = start; first <= end; first++)
            array[first] = tmp[first];


        System.out.println("merge is " + Arrays.toString(array));

    }

    public static void mergeSort(int[] array, int start, int end, int[] tmp) {

        if (start >= end)
            return;
        int middle = ((end + start) >> 1);
        mergeSort(array, start, middle, tmp);// 遞歸劃分左邊的數組
        mergeSort(array, middle + 1, end, tmp);// 遞歸劃分右邊的數組
        merge(array, start, middle, end, tmp);// 對有序的兩個數組進行合併成一個有序的數組
    }

}
相關文章
相關標籤/搜索