归并排序 -- 算法小结

对于一个int数组,请编写一个归并排序算法,对数组元素排序。

给定一个int数组A及数组的大小n,请返回排序后的数组。

测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]

import java.util.*;

public class MergeSort {
    public int[] mergeSort(int[] A, int n) {
        // write code here
       sort(A,0,n-1);
        return A;
    }
    public void sort(int[] A,int left,int right){
        if(left<right){
            int middle = (left+right)/2;  //划分区间
            sort(A,left,middle);       //分别对左右区间进行划分
            sort(A,middle+1,right);
            merge(A,left,middle,right);  //对两个区间进行合并
        }
    }
    public void merge(int[] A,int left,int middle,int right){
        int[] tem = new int[right-left+1];  //创建临时数组
        int leftindex=left;  //左区间数组游标
        int rightindex=middle+1;  //右区间数组游标
        int temindex=0;   //临时数组游标
        //对两边进行排序  结果放在临时数组里面
        while(leftindex<=middle&&rightindex<=right){
        if( A[leftindex]>A[rightindex]){
            tem[temindex++]=A[rightindex++];
        }else{
            tem[temindex++]=A[leftindex++];
        }
        }
        //直至有一个区间的数全比较完  将另一数组剩下的数直接添加至临时数组
        while(leftindex<=middle){
            tem[temindex++]=A[leftindex++];
        }
        while(rightindex<=right){
            tem[temindex++]=A[rightindex++];
        }
        temindex=0;
        //将临时数组的元素依次替换待排序数组 
        while((temindex+left)<=right){
            A[temindex+left]=tem[temindex];
            temindex++;
        }
    }
    }

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值