归并排序(Merge Sort)也是一种常用的排序方法,“归并”的含义是将两个或两个以上的有序子序列合并成一个新的有序子序列。如图10-11为两组有序子序列的归并,有序子序列{4,25,34,56,69,74}和{15,26,34,47,52},通过归并把它们合并成一个有序子序列{4,15,25,26,34,34,47,52,56,69,74}。
package ch02;
import util.ArrayUtil;
public class MergeSort {
public static void main(String[] args) {
// int[] array = new int[]{2,8,6,4,3,9,1};
// int[] array = new int[]{58,46,72,95,84,25,37,58,63,12};
int[] array = new int[]{45,34,67,95,78,12,26,45};
mergeSort(array);
ArrayUtil.display(array);
}
public static void mergeSort(int[] arr){
int[] tmpArr = new int[arr.length];
mergeSort(arr,tmpArr,0,arr.length-1);
}
public static void mergeSort(int[] arr,int[] tmpArr,int left,int right){
if(left<right){
int center = (left+right)/2;
mergeSort(arr,tmpArr,left,center);
mergeSort(arr,tmpArr,center+1,right);
merge(arr,tmpArr,left,center,right);
}
}
public static void merge(int[] arr,int[] tmpArr,int leftPos,int center,int rightEnd){
int leftEnd = center;
int rightPos = center+1;
int tmpPos = leftPos;
int nums = rightEnd - leftPos + 1;
while(leftPos<=leftEnd&&rightPos<=rightEnd){
if(arr[leftPos]<arr[rightPos]){
tmpArr[tmpPos++] = arr[leftPos++];
}else{
tmpArr[tmpPos++] = arr[rightPos++];
}
}
while(leftPos<=leftEnd){
tmpArr[tmpPos++] = arr[leftPos++];
}
while(rightPos<=rightEnd){
tmpArr[tmpPos++] = arr[rightPos++];
}
for(int i= 0;i<nums;i++,rightEnd--){
arr[rightEnd] = tmpArr[rightEnd];
}
}
}