public class MergeSort { public static void main(String[] args) {// int[] arr={8,2,7,4,5,3,6,1,0}; int []arr = new int[80000000]; for (int i = 0; i < 80000000; i++) { arr[i] = (int) (Math.random() * 8000000); } int[] temp =new int[arr.length]; long start= System.currentTimeMillis(); mergeSort(arr,0,arr.length-1,temp); long end= System.currentTimeMillis(); System.out.println("time="+(end-start));// mergeSort(arr,0,arr.length-1,temp);// System.out.println(Arrays.toString(arr)); } public static void mergeSort(int[] arr, int left, int right, int[] temp) { if(left < right) { int mid = (left + right) / 2; //递归分解 mergeSort(arr, left, mid, temp); mergeSort(arr, mid + 1, right, temp); //递归合并 merge(arr, left, mid, right, temp); } } public static void merge(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]; t += 1; i += 1; } else { temp[t] = arr[j]; t += 1; j += 1; } } //剩余的数继续插入到temp中 while (i <= mid) { temp[t] = arr[i]; t += 1; i += 1; } //剩余的数继续插入到temp中 while (j <= right) { temp[t] = arr[j]; t += 1; j += 1; } //合并 t = 0; int tempLeft = left; while (tempLeft <= right) { arr[tempLeft] = temp[t]; t += 1; tempLeft += 1; } }}