1 public class MergeSort { 2 public static void main(String[] args) { 3 int[] arr = {9,6,11,3,5,12,8,7,10,15,14,4,1,13,2}; 4 int[] temp = new int[arr.length]; 5 sort(arr,0,arr.length-1,temp); 6 print(arr); 7 } 8 static void sort(int[]arr,int left, int right,int[] temp) { 9 int mid = (right-left)/2+left; 10 if(left<right) { 11 sort(arr,left,mid,temp);//分,自顶向下,递归 12 sort(arr,mid+1,right,temp); 13 } 14 merge(arr,temp,left,right);//治,和,回溯 15 } 16 static void merge(int[] arr,int[] temp,int left,int right) { 17 int k =0; 18 int mid = (right-left)/2+left; 19 int Left = left;//左序列指针 20 int Mid = mid+1;//右序列指针 21 22 while(Mid<=right && Left<= mid) temp[k++] = arr[Left]<=arr[Mid] ? arr[Left++] : arr[Mid++]; 23 while(Mid<=right) temp[k++] = arr[Mid++];//两正序数组合并一正序数组 24 while(Left<=mid) temp[k++] = arr[Left++]; 25 26 Left = left;//初始化,将合并后的正序数组给原数组传回排好序的值 27 for(int i = 0; i<right-left+1;i++) { 28 arr[Left++] = temp[i]; 29 } 30 } 31 static void swap(int[] arr,int i,int j) { 32 int temp=arr[i]; 33 arr[i]=arr[j]; 34 arr[j]=temp; 35 } 36 static void print(int[] arr) { 37 for(int i=0;i<arr.length;i++) { 38 System.out.print(arr[i]+" "); 39 } 40 } 41 }
归并排序是稳定的排序,十分高效的排序,利用完全二叉树特性排序,性能很好。java中Arrays.sort()采用了一种名为TimSort的排序算法,就是归并排序的优化版本。每次合并操作的平均时间复杂度为O(n),而完全二叉树的深度为|log2n|。总的平均时间复杂度为O(nlog2n)。而且,归并排序的最好,最坏,平均时间复杂度均为O(nlog2n)。
原文:https://www.cnblogs.com/flyer-ovo/p/14797330.html