package primary_01;/** 归并排序* 1.算法实现* 2.验证算法的正确性* 3.分析算法的复杂度*/public class Merge_sort {public static void main(String[] args) {int arr []= {2,1,6,5,9,8,2020,199};sort(arr, 0, arr.length-1);for (int i : arr) {System.out.print(i+" ");}}/** 归并排序* 1.划分的过程* mid * 2.归并的过程* merge* 3.递归的过程* 递归的实质*/private static void sort(int[] arr,int l,int h) {if(h <= l || arr.length<2) {return;}int mid=l+((h-l)>>1);// int mid=l+(h-l)/2;sort(arr,l,mid);sort(arr,mid+1,h);merge(arr,l,mid,h);}private static void merge(int[] arr, int l, int mid, int h) {int help [] =new int [h-l+1];int p1=l;int p2=mid+1;int index;for(index=0;p1<=mid && p2<=h ; index++) {help[index] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];}while(p2 <= h) {help[index++]=arr[p2++];}while(p1 <= mid) {help[index++]=arr[p1++];}for(int i=0;i<help.length;i++) {arr[l++]=help[i];}}}
/*** 算法复杂度分析* 时间复杂度:O(n*logn)* master公式运用* master公式的使用T(N) = a*T(N/b) + O(N^d)1) log(b,a) > d -> 复杂度为O(N^log(b,a)) 2) log(b,a) = d -> 复杂度为O(N^d * logN) 3) log(b,a) < d -> 复杂度为O(N^d)对于归并排序:T(N)=2*T(N/2)+O(N) 复杂度为O(N*logN)*/