public class MergeSort {

    /*合并两个有序序列*/
    public static void merge(int[] array, int[] temp, int low, int middle, int high) {
        //array[low~middle]和array[middle+1~high]是两个有序表

        //index1是array[low~middle]的下标,index2是array[middle+1~high]的下标,tempIndex是temp的下标
        int index1 = low, index2 = middle + 1, tempIndex = low;

        for (; index1 <= middle && index2 <= high; ) {
            //依次比较两个序列的大小,将较小的放入temp序列,这里把“<”改成“>”则是按从大到小排序
            if (array[index1] < array[index2])
                temp[tempIndex++] = array[index1++];
            else
                temp[tempIndex++] = array[index2++];
        }

        if (index1 > middle) {
            do {
                //将array[middle+1~high]余下部分复制到temp序列
                temp[tempIndex++] = array[index2++];
            } while (index2 <= high);
        } else {
            do {
                //将array[low~middle]余下部分复制到temp序列
                temp[tempIndex++] = array[index1++];
            } while (index1 <= middle);
        }

        //将temp[low~high]序列复制到原序列
        System.arraycopy(temp, low, array, low, high + 1 - low);

    }

    /* 归并排序函数,递归方式,自顶向下 */
    public static void upBottomsort(int[] array, int[] temp, int low, int high) {
        if (low < high) {
            int middle = (low + high) / 2;
            upBottomsort(array, temp, low, middle);                /* 递归调用,将子序列array[low~middle]归并为有序序列 */
            upBottomsort(array, temp, middle + 1, high);           /* 递归调用,将子序列array[middle+1~high]归并为有序序列 */
            merge(array, temp, low, middle, high);                 /* 将子序列array[low~middle]和array[middle+1~high]进行归并 */
        }
    }

    /* 归并排序函数,非递归方式,自底向上 */
    public static void bottomUpsort(int[] array, int[] temp) {
        int size = 1, low, middle, high, n = array.length;
        while (size <= n - 1) {
            low = 0;
            while (low + size <= n - 1) {
                middle = low + size - 1;
                high = middle + size;
                if (high > n - 1)//第二个序列个数不足size
                    high = n - 1;
                merge(array, temp, low, middle, high);
                low = high + 1;//下一次归并时第一个序列的开始下标
            }
            size *= 2;//范围扩大一倍
        }
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        int[] array = {12, 23, 9, 24, 11, 29, 30, 22, 45, 86, 50, 66, 38, 90, 10, 43};
        System.out.println("before sort:");
        for (int anArray : array) {
            System.out.print(anArray + " ");
        }
        System.out.println();
        int[] temp = new int[array.length];
        //递归方式
//        upBottomsort(array, temp, 0, array.length - 1);
        //非递归方式
        bottomUpsort(array, temp);
        System.out.println("after sort:");
        for (int anArray : array) {
            System.out.print(anArray + " ");
        }
    }
}

MartinDai
1.5k 声望236 粉丝

保持学习心态,持续成长