代码
public class MergeSort {
public static void main(String[] args) {
// int[] arr = {8,4,5,7,1,3,2,6};
// int[] temp = new int[arr.length];
// System.out.println("排序前:" +Arrays.toString(arr));
// mergeSort(arr, 0, arr.length - 1, temp);
// System.out.println("排序后:" +Arrays.toString(arr));
int[] arr = new int[80000000];
int[] temp = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
//生成一个【0,8000000】的数
arr[i] = (int)(Math.random() * 8000000);
}
long start = System.currentTimeMillis();
mergeSort(arr, 0, arr.length - 1, temp);
long end = System.currentTimeMillis();
System.out.println("总共花费:" + (end - start));
}
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;//指向temp的当前索引
while(i <= mid && j <= right){
if(arr[i] < arr[j]){
temp[t] = arr[i];
i += 1;
t += 1;
}else{
temp[t] = arr[j];
j += 1;
t += 1;
}
}
while(i <= mid){
temp[t] = arr[i];
i += 1;
t += 1;
}
while(j <= right){
temp[t] = arr[j];
j += 1;
t += 1;
}
t = 0;
int tempLeft = left;
while(tempLeft <= right){
arr[tempLeft] = temp[t];
t += 1;
tempLeft += 1;
}
}
}
效率
//8000 0000 15156ms
//800 0000 1378ms
//80 0000 1118ms
//8 0000 28ms