package basic_class_01;
/**
* @Author qgfzzzzzz
* @Date 19-3-1
* @Version 1.0
*
* This is merge sort
* T(N) = 2 * T(N /2) + O(N)
*
* master : T(N) = a * T(N / b) + o(N ^ d)
* 1) log(b, a) > d time : o(n * log(b, a))
* 2) log(b, a) = d time : o(n ^ d * logn)
* 3) log(b, a) < d time : o(n ^ d)
*
* a = 2, b = 2, d = 1 --> o(n * logn)
*/
public class Code_05_MergeSort {
public static void mergeSort(int[] arr){
if(arr == null || arr.length < 2){
return;
}
mergeSort(arr, 0, arr.length - 1);
}
public static void mergeSort(int[] arr, int l, int r){
if(l == r){
return;
}
int mid = l + ((r - l) >> 1);
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void merge(int[] arr, int l, int m, int r){
int[] p = new int[r - l + 1];
int i = 0;
int p1 = l;
int p2 = m + 1;
while(p1 <= m && p2 <= r){
p[i++] = arr[p1] > arr[p2] ? arr[p2++] : arr[p1++];
}
while(p1 <= m){
p[i++] = arr[p1++];
}
while(p2 <= r){
p[i++] = arr[p2++];
}
for(i = 0; i < p.length; i++){
arr[l + i] = p[i];
}
}
public static void main(String[] args){
int[] arr = {4, 9, 7, 2, 1, 6, 3, 8, 5};
mergeSort(arr);
for (int t :
arr) {
System.out.print(t + " ");
}
}
}