AcWing 787. 归并排序(Java)
原题链接
简单
作者:
火球大的脸盆
,
2022-07-06 18:43:01
,
所有人可见
,
阅读 140
import java.io.*;
public class Main {
public static int[] tmp = new int[100010];
public static void merge_sort(int q[], int l, int r) {
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r) {
if (q[i] <= q[j]) tmp[k++] = q[i++];
else tmp[k++] = q[j++];
}
while (i <= mid) tmp[k++] = q[i++];
while (j <= r) tmp[k++] = q[j++];
for (i = l, j = 0; i <= r; i++, j++) q[i] = tmp[j];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] in = br.readLine().split(" ");
int[] q = new int[n];
for (int i = 0; i < n; i++) {
q[i] = Integer.parseInt(in[i]);
}
merge_sort(q, 0, n - 1);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for (int i = 0; i < n; i++) {
bw.write(q[i] + " ");
bw.flush();
}
}
}