歸并排序運(yùn)用分治的思想,把大的問題逐部分解成能夠解決的小問題.
時(shí)間復(fù)雜度為nlogn.
Ps:使用引用傳遞的方法把臨時(shí)數(shù)組賦值進(jìn)去,這樣就可以沒必要每次都生成一個(gè)新的數(shù)組.
代碼:
/**
* Created by Hammy on 2018/3/1.
*/
public class MergeSort
{
/**
* 二路歸并排序
*/
public static void sort(int[] array){
int[] tempArray = new int[array.length];
mergeSort(array,tempArray,0,array.length-1);
}
private static void mergeSort(int[] array,int[] tempArray,int left,int right){
if(left>=right)
return;
int mid=left+((right-left)>>1);
mergeSort(array,tempArray,left,mid);
mergeSort(array,tempArray,mid+1,right);
merge(array,tempArray,left,mid,right);
}
private static void merge(int[] array,int[] tempArray,int left,int mid,int right){
int tempIndex = left;
int copyIndex = left;
int rightStart = mid+1;
while(left<=mid&&rightStart<=right){
if(array[left]<array[rightStart]){
tempArray[tempIndex++]=array[left++];
}else{
tempArray[tempIndex++]=array[rightStart++];
}
}
while(left<=mid)
tempArray[tempIndex++]=array[left++];
while(rightStart<=right)
tempArray[tempIndex++]=array[rightStart++];
//開始復(fù)制
while(copyIndex<=right){
array[copyIndex]=tempArray[copyIndex++];
}
}