归并排序
递归是真的烧脑。
public static void main(String[] args) {
int[] arr = new int[80000];
for (int a = 0; a < 80000; a++) {
arr[a] = (int) (Math.random() * 8000000);
}
long l = System.currentTimeMillis();
mergeSort(arr,0,arr.length-1 );
long l1 = System.currentTimeMillis();
System.out.println(l1 - l);
}
public static void mergeSort ( int[] arr, int low, int high){
if (low >= high) {
return;
}
int mid = (low + high) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
merge(arr, low, high, mid);
}
public static void merge ( int[] arr, int low, int high, int mid){
int i = low;
int j = mid + 1;
int t = 0;
int[] res = new int[high - low + 1];
while (i <= mid && j <= high) {
if (arr[i] <= arr[j]) {
res[t] = arr[i];
i++;
t++;
} else {
res[t] = arr[j];
j++;
t++;
}
}
while (i <= mid) {
res[t] = arr[i];
i++;
t++;
}
while (j <= high) {
res[t] = arr[j];
j++;
t++;
}
for (int k = low; k <= high; k++) {
arr[k] = res[k - low];
}
}