AcWing 787. 归并排序
原题链接
简单
作者:
Broken_
,
2024-09-13 19:12:45
,
所有人可见
,
阅读 2
java 代码
import java.util.Scanner;
public class Main {
final static int N = 1000000;
private static int[] temp = new int[N];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
mergeSort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void mergeSort(int[] arr, int l, int r) {
if (l >= r) return;
int mid = (l + r) >> 1;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r) {
if (arr[i] <= arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
//将剩余元素复制到temp数组中
while (i <= mid) temp[k++] = arr[i++];
while (j <= r) temp[k++] = arr[j++];
//将temp数组中的元素复制回arr数组
for (int t = l; t <= r; t++)
arr[t] = temp[t - l];
}
}