还是这个老哥写的好:https://blog.51cto.com/13733462/2115396
二路合并排序的基本思想是:对于两个有序表合并,初始时, 把含有n个结点的待排序序列看作有n个长度为1的有序子表所组成,将它们依次两两合并,得到长度为2的若干有序子表,再对这些子表进行两两合并,一直重复到长度为n,排序完成。
1 package Sort; 2 import java.util.Arrays; 3 4 public class MergeSort { 5 6 public static void mergeSort(int [] arr){ 7 8 if(arr ==null||arr.length<2){ 9 return ; 10 } 11 sortProcess(arr, 0, arr.length-1); 12 } 13 14 public static void sortProcess(int []arr,int L,int R){ 15 if(L==R){ 16 return; 17 } 18 int mid = L+((R-L)>>1);//等同于(L+R)/2 19 sortProcess(arr, L, mid); 20 sortProcess(arr, mid+1, R); 21 merge(arr,L,mid,R); 22 } 23 24 public static void merge(int []arr,int L,int mid,int R){ 25 int[] help= new int[R-L+1]; 26 int i =0; 27 int p1 = L; 28 int p2 = mid+1; 29 while(p1<=mid && p2<=R){ 30 if(arr[p1]<arr[p2]){ 31 help[i] = arr[p1]; 32 p1++; 33 } 34 else{ 35 help[i]=arr[p2]; 36 p2++; 37 } 38 i++; 39 } 40 while(p1<=mid){ 41 help[i++] = arr[p1++]; 42 } 43 while(p2<=R){ 44 help[i++]=arr[p2++]; 45 } 46 47 for(i=0;i<help.length;i++){//把排序好的help拷贝回原数组 48 arr[L] = help[i]; 49 L++; 50 } 51 52 } 53 public static void comparator(int[] arr) { 54 Arrays.sort(arr);//系统排序绝对正确的方法 55 } 56 57 public static int[] generateRandomArray(int maxSize, int maxValue) {//随机数发生器 58 //Math.random 产生一个double [0,1) 59 60 int[] arr = new int[(int) ((maxSize + 1) * Math.random())];//产生一个随机长度的数组 61 for (int i = 0; i < arr.length; i++) { 62 arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());//产生一个随机数,两个随机数减一下 63 } 64 return arr; 65 } 66 67 // for test 68 public static int[] copyArray(int[] arr) { 69 if (arr == null) { 70 return null; 71 } 72 int[] res = new int[arr.length]; 73 for (int i = 0; i < arr.length; i++) { 74 res[i] = arr[i]; 75 } 76 return res; 77 } 78 79 // for test 80 public static boolean isEqual(int[] arr1, int[] arr2) { 81 if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) { 82 return false; 83 } 84 if (arr1 == null && arr2 == null) { 85 return true; 86 } 87 if (arr1.length != arr2.length) { 88 return false; 89 } 90 for (int i = 0; i < arr1.length; i++) { 91 if (arr1[i] != arr2[i]) { 92 return false; 93 } 94 } 95 return true; 96 } 97 98 // for test 99 public static void printArray(int[] arr) { 100 if (arr == null) { 101 return; 102 } 103 for (int i = 0; i < arr.length; i++) { 104 System.out.print(arr[i] + " "); 105 } 106 System.out.println(); 107 } 108 109 110 public static void main(String[] args) { 111 112 int testTime = 500000; 113 int maxSize = 10; 114 int maxValue = 100; 115 boolean succeed = true; 116 for (int i = 0; i < testTime; i++) { 117 int[] arr1 = generateRandomArray(maxSize, maxValue); 118 int[] arr2 = copyArray(arr1); 119 mergeSort(arr1); 120 comparator(arr2); 121 if (!isEqual(arr1, arr2)) { 122 succeed = false; 123 break; 124 } 125 } 126 System.out.println(succeed ? "Nice!" : "Fucking fucked!"); 127 128 int[] arr = generateRandomArray(maxSize, maxValue); 129 printArray(arr); 130 mergeSort(arr); 131 printArray(arr); 132 133 } 134 135 }