【2020.1.31】
原始数据:6,4,3,7,5,1,2,6
预期排序过程:
java实现:(此算法不会改变相同value的相对顺序)
import java.io.*;
import java.util.*;
import java.lang.*;class MergeSort{
public static void main(String[] args) throws Exception {
int[] array={6,4,3,7,5,1,2,6};
sort(array);
println(array);
}
private static void println(int[] arr)
{
for(int i:arr)
System.out.print(" "+i);
System.out.println();
}
public static void sort(int[] src) throws Exception
{
System.out.print("start sort:");
println(src);
if(src.length>1)
{
int leftLength=(int)Math.ceil((double)src.length/2);
int rightLength=src.length-leftLength;
int[] leftArray=new int[leftLength];
int[] rightArray=new int[rightLength];
System.arraycopy(src,0,leftArray,0,leftLength);
System.arraycopy(src,leftLength,rightArray,0,rightLength);
sort(leftArray);
sort(rightArray);
//归并
int[] result= merge(leftArray,rightArray);
System.arraycopy(result,0,src,0,result.length);
}
}
private static int[] merge(int[] leftArray,int[] rightArray)
{
int[] array=new int[leftArray.length+rightArray.length];
int arrayIndex=0;
int left=0;
int right=0;
while(left<leftArray.length&&right<rightArray.length)
{
int leftValue=leftArray[left];
int rightValue=rightArray[right];
if(leftValue<=rightValue)
{
left++;
array[arrayIndex++]=leftValue;
}
else
{
right++;
array[arrayIndex++]=rightValue;
}
}
if(left<leftArray.length)
System.arraycopy(leftArray,left,array,arrayIndex,leftArray.length-left);
else
System.arraycopy(rightArray,right,array,arrayIndex,rightArray.length-right);
System.out.print("merge result:");
println(array);
return array;
}
}