/**
* 自底向上的归并排序,平常见的都是自顶向下的归并,这里实现一种自下而上的归并,供参考
*/
import java.util.*;
public class Solution {
public static void main(String args[]) {
int a[] = new int[]{8, 9, 2, 3, 1, 4, 6, 7, 5, 0,-1,-3,-2};
Solution s = new Solution();
System.out.print("排序之前:");
s.show(a);
s.sort(a);
}
//打印数组
public void show(int a[]) {
for (Integer i : a)
System.out.print(i + " ");
System.out.println();
}
//交换数值的函数
public void swap(int a[], int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
int aux[]; //辅助空间
public void sort(int a[]){
int n=a.length;
aux=new int[n];
for(int size=1;size<n;size=size*2){ //size确保自下而上
for(int low=0;low<n-size;low=low+2*size)
merge(a,low,low+size-1,Math.min(n-1,low+size+size-1));
}
System.out.print("自底向上的归并:");
show(a);
}
public void merge(int a[], int low, int mid, int high) {
if(low>=high)
return ;
int i = low, k = low, j = mid + 1;
for(k=low;k<=high;k++) aux[k]=a[k]; //复制到辅助数组
k=low;
for(k=low;k<=high;k++)
if(i>mid) a[k]=aux[j++];
else if(j>high) a[k]=aux[i++];
else if(aux[i]>=aux[j]) a[k]=aux[j++];
else
a[k]=aux[i++];
}
}