package com.abin.lee.algorithm.merge;
import java.util.Arrays;
/**
* 歸并排序
*/
public class MergeSort {
public static void main(String[] args) {
int[] input = {2,7,3,9,1,6,0,5,4,8};
MergeSort.sort(input, 0, input.length-1);
System.out.println("input="+Arrays.toString(input));
}
//首先分而自治
/**
* 歸并排序
* 簡介:將兩個(或兩個以上)有序表合并成一個新的有序表 即把待排序序列分為若干個子序列,每個子序列是有序的。然后再把有序子序列合并為整體有序序列
* 時間復雜度為O(nlogn)
* 穩定排序方式
* @param nums 待排序數組
* @return 輸出有序數組
*/
public static int[] sort(int[] input,int low,int high){
int middle = (low+high)/2;
if(low<high){
//左邊
sort(input,low,middle);
//右邊
sort(input,middle+1,high);
//左右歸并
merge(input,low,high,middle);
}
return input;
}
public static void merge(int[] input,int low,int high,int middle){
int[] temp = new int[high-low+1];
int i = low;//左指針
int j = middle+1;//右指針
int k=0;
// 把較小的數先移到新數組中
while(i<=middle&&j<=high){
if(input[i]<input[j]){
temp[k++] = input[i++];
}else{
temp[k++] = input[j++];
}
}
// 把左邊剩余的數移入數組
while(i<=middle){
temp[k++] = input[i++];
}
// 把右邊邊剩余的數移入數組
while(j<=high){
temp[k++] = input[j++];
}
// 把新數組中的數覆蓋input數組
for(int m=0;m<temp.length;m++){
input[m+low] = temp[m];
}
}
}