归并排序
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = new int[800000];
for (int i = 0; i < 800000; i++) {
arr[i] = (int) (Math.random() * 800000);
}
int temp[] = new int[arr.length];
long startTime = System.currentTimeMillis();
mergeSort(arr,0,arr.length-1,temp);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
}
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[j];
j++;
t++;
}else {
temp[t] = arr[i];
i++;
t++;
}
}
while(i<=mid){
temp[t] = arr[i];
i++;
t++;
}
while(j<=right){
temp[t] = arr[j];
j++;
t++;
}
t=0;
int tempLeft = left;
while(tempLeft<=right){
arr[tempLeft] = temp[t];
t++;
tempLeft++;
}
}
}