对于一个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++;
}
}
}