转载请注明出处:http://blog.csdn.net/droyon/article/details/8790259
/**
* 归并排序
* 合并两个已排序好的数组花费线性时间,归并排序用到了这个性质。
* 采用分治策略,递归的分,直到只有一个或者两个元素,结束递归。采用merge函数合并。
* @author
*
*/
public class MergeSort {
private static int[] array = new int[]{1,8,2,9,3,7,11,23,90,4,5};
private static int[] tempArray = new int[array.length];
public static void main(String args[]){
System.out.println("排序前");
printArray(array);
System.out.println("\n排序后");
mergeSort(0,array.length-1);
printArray(array);
}
private static void mergeSort(int left,int right){
if(left<right){
int center = (left+right)/2;
mergeSort(center+1, right);
mergeSort(left, center);
merge(left,center,right);
}
}
private static int count=0;
private static void merge(int left,int center,int right){
int leftPos = left;
int leftEnd = center;
int rightPos = center+1;
int rightEnd = right;
int tempPos = leftPos;
while(leftPos<=leftEnd&&rightPos<=rightEnd){
if(array[leftPos]<=array[rightPos]){
tempArray[tempPos++] = array[leftPos++];
}else{
tempArray[tempPos++] = array[rightPos++];
}
}
while(leftPos<=leftEnd){
tempArray[tempPos++] = array[leftPos++];
}
while(rightPos<=rightEnd){
tempArray[tempPos++] = array[rightPos++];
}
//需要查看每次排序结果,打开以下注释
// System.out.println("第"+(count++)+"次tempArray结果"+"["+left+"-"+center+"-"+right+"]");
// printArray(tempArray);
// System.out.println("array");
// printArray(array);
for(int i=left;i<=rightEnd;i++){
array[i] = tempArray[i];
}
// System.out.println("调整之后array");
// printArray(array);
// System.out.println();
}
public static void printArray(int[] array){
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
}
}
结果:
排序前
1 8 2 9 3 7 11 23 90 4 5
排序后
1 2 3 4 5 7 8 9 11 23 90