码迷,mamicode.com
首页 > 编程语言 > 详细

排序算法之归并排序迭代实现

时间:2019-02-02 23:07:18      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:算法   .so   system   out   int end   处理   复制   rate   时空   

快要过节了,目前先把代码贴上,后续加上图示和复杂度信息

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 

排序算法之归并排序迭代实现

标签:算法   .so   system   out   int end   处理   复制   rate   时空   

原文地址:https://www.cnblogs.com/ITBlock/p/10349200.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!