public class MergeSort {
//排序函数,排序思路,对一个数组排序,只需要把前半部分排序,后半部分排序,然后调用merge函数即可。
private static <AnyType extends Comparable<? super AnyType>>
void mergeSort(AnyType[] a,AnyType[] tmpArray,int left,int right){
if(left<right){
int center=(left+right)/2;
mergeSort(a,tmpArray,left,center);
mergeSort(a,tmpArray,center+1,right);
merge(a,tmpArray,left,center,right);
}
}
//对a数组排序
public static <AnyType extends Comparable<? super AnyType>>
void mergeSort(AnyType[] a){
@SuppressWarnings("unchecked")
AnyType[] tmpArray=(AnyType[])new Comparable[a.length];
mergeSort(a,tmpArray,0,a.length-1);
}
//对两个已经排序好的数组进行排序,用tmp调度。
private static <AnyType extends Comparable<? super AnyType>> void
merge(AnyType[] a,AnyType[] tmp,int left,int center,int right){
int _leftend=center;
int _left=left,_center=center+1,_right=right;
int myleft=left;
while(_left<=_leftend&&_center<=right){
if(a[_left].compareTo(a[_center])<0){
tmp[myleft++]=a[_left++];
}else{
tmp[myleft++]=a[_center++];
}
}
while(_left<=_leftend){
tmp[myleft++]=a[_left++];
}
while(_center<=_right){
tmp[myleft++]=a[_center++];
}
for(int i=left;i<=right;i++){
a[i]=tmp[i];
}
}
//排序函数,排序思路,对一个数组排序,只需要把前半部分排序,后半部分排序,然后调用merge函数即可。
private static <AnyType extends Comparable<? super AnyType>>
void mergeSort(AnyType[] a,AnyType[] tmpArray,int left,int right){
if(left<right){
int center=(left+right)/2;
mergeSort(a,tmpArray,left,center);
mergeSort(a,tmpArray,center+1,right);
merge(a,tmpArray,left,center,right);
}
}
//对a数组排序
public static <AnyType extends Comparable<? super AnyType>>
void mergeSort(AnyType[] a){
@SuppressWarnings("unchecked")
AnyType[] tmpArray=(AnyType[])new Comparable[a.length];
mergeSort(a,tmpArray,0,a.length-1);
}
//对两个已经排序好的数组进行排序,用tmp调度。
private static <AnyType extends Comparable<? super AnyType>> void
merge(AnyType[] a,AnyType[] tmp,int left,int center,int right){
int _leftend=center;
int _left=left,_center=center+1,_right=right;
int myleft=left;
while(_left<=_leftend&&_center<=right){
if(a[_left].compareTo(a[_center])<0){
tmp[myleft++]=a[_left++];
}else{
tmp[myleft++]=a[_center++];
}
}
while(_left<=_leftend){
tmp[myleft++]=a[_left++];
}
while(_center<=_right){
tmp[myleft++]=a[_center++];
}
for(int i=left;i<=right;i++){
a[i]=tmp[i];
}
}
}
测试:
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] nums=new Integer[]{1,5,1,6,2,7,3,5,2,8,3,4};
//Shellsort.shellsort(nums);
//Heapsort.heapsort(nums);
MergeSort.mergeSort(nums);
for(Integer num:nums){
System.out.print(num+" ");
}
效果:
1 1 2 2 3 3 4 5 5 6 7 8