[转]归并排序
(java版)
public class mergingSort {
public static void merge(int[] a,int left, int center, int right){
int[] tmpArr = new int[a.length];
int mid = center + 1;
int third = left;
//third记录中间数组的索引
int tmp = left;
while(left <= center && mid <= right){
//从两个数组中取出最小的放入中间数组
if(a[left] <= a[mid]){
tmpArr[third++] = a[left++];
}else{
tmpArr[third++] = a[mid++];
}
}
//剩余部分一次放入中间数组
while(mid <= right){
tmpArr[third++] = a[mid++];
}
while(left <= center){
tmpArr[third++] = a[left++];
}
//将中间数组中的内容复制灰原数组
while(tmp <= right){
a[tmp] = tmpArr[tmp++];
}
}
public static void sort(int[] a, int left, int right){
if(left < right){
//找出中间索引
int center = (left + right)/2;
//对左边数组进行递归
sort(a,left,center);
//对右边数组进行递归
sort(a,center+1,right);
//合并
merge(a,left,center,right);
}
}
public static void main(String[] args) {
int[] a = {0,2,5,43,32,65,43,21,87,1};
sort(a,0,a.length-1);
for(int i =0; i<a.length; i++)
System.out.print(a[i]+" ");
}
}