歸併排序是利用分治的思想進行排序的策略。code
能夠理解爲一個二叉樹,經過深層遞歸拆成小的序列。排序
分紅A,B兩個小的序列,若是A序列的有序序列小於B有序序列的最小值,則A放在一個臨時隊列的最前面,以此類推。遞歸
咱們爲了便於理解能夠將歸併過程理解成Map/Reduce的過程。隊列
Map圖片
public static void main(String[] args) { int[] arr = {8,4,5,7,1,3,6,2}; sort(arr); System.out.println(Arrays.toString(arr)); } private static void sort(int[] arr){ int[] temp = new int[arr.length]; map(arr,0,arr.length-1,temp); } private static void map(int[] arr,int left,int right,int[] temp){ if(left < right){ int mid = (left + right) / 2; map(arr,left,mid,temp); map(arr,mid+1,right,temp); reduce(arr,left,mid,right,temp); } }
Reduceit
private static void reduce(int[] arr,int left,int mid,int right,int[] temp){ int i = left; int j = mid + 1; int t = 0; while (i<=mid && j<=right){ if(arr[i]<=arr[j]){ temp[t++] = arr[i++]; }else { temp[t++] = arr[j++]; } } while (i<=mid){ temp[t++] = arr[i++]; } while (j<=right){ temp[t++] = arr[j++]; } t = 0; while (left <= right){ arr[left++] = temp[t++]; } }
輸出結果二叉樹
[1, 2, 3, 4, 5, 6, 7, 8]