0
点赞
收藏
分享

微信扫一扫

数据结构 归并排序 实现实例

爱动漫建模 2022-01-12 阅读 52

文章目录

用图了解归并排序

在这里插入图片描述

在这里插入图片描述

class Msort

import java.util.Arrays;

public class Msort {
    public static void main(String[] args) {
        int[] arrays= new int[]{1,4,2,3,7,6,5,9,8,0};
        //临时数组
        int[] temp=new int[arrays.length];

        sort(arrays,0, arrays.length-1,temp);
        System.out.println(Arrays.toString(arrays));
    }
    public static void sort(int [] arrays,int left,int right,int [] temp){
        if(left<right){
            //求取中间值
            int mid=(left+right)/2;
            //左边继续分
            sort(arrays,left,mid,temp);
            //右边继续分
            sort(arrays,mid+1,right,temp);
            //合并数据
            sum(arrays,left,right,mid,temp);
        }
    }

    /**
     * 合并元素
     * @param arrays
     * @param left
     * @param right
     * @param mid
     * @param temp
     */
    public static void sum(int[] arrays,int left,int right,int mid,int[] temp){
       int i=left;
       int j=mid+1;
       //指向临时数组下标
        int t=0;
        while (i<=mid&&j<=right){
            if(arrays[i]>arrays[j]){
                temp[t]=arrays[j];
                t++;
                j++;
            }else{
                temp[t]=arrays[i];
                t++;
                i++;
            }
        }
        while (i<=mid){
            temp[t]=arrays[i];
            t++;
            i++;
        }
        while(j<=right){
            temp[t]=arrays[j];
            t++;
            j++;
        }
        int tempIndex=left;
        int k=0;
        while(tempIndex<=right){
            arrays[tempIndex]=temp[k];
            tempIndex++;
            k++;
        }
    }
}

举报

相关推荐

0 条评论