AcWing 787. 归并排序 (Java)
原题链接
简单
作者:
Georgehu
,
2020-03-27 00:05:54
,
所有人可见
,
阅读 1099
import java.util.Scanner;
import java.io.BufferedInputStream;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
mergeSort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
private static void mergeSort(int[] arr, int left, int right) {
if (left >= right) return;
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
int k = 0, i = left, j = mid + 1;
int[] tmp = new int[right - left + 1];
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
tmp[k++] = arr[i++];
} else {
tmp[k++] = arr[j++];
}
}
while (i <= mid) {
tmp[k++] = arr[i++];
}
while (j <= right) {
tmp[k++] = arr[j++];
}
for (i = left, j = 0; i <= right; i++, j++) {
arr[i] = tmp[j];
}
}
}