题目描述
归并排序
样例
import java.io.BufferedInputStream;
import java.util.Scanner;
/*
中间分开:对左右两边都递归排序
开一个结果数组,双指针分别指向左右区间的最小值(也就是最左位置)
比较大小后放入结果数组,判断是否还有剩下的,有就全部
*/
public class Main {
private static int[] mergeSort(int[] arr, int left, int right) {
if (left >= right) {
return arr;
}
int mid = (left + right) / 2;
arr = mergeSort(arr, left, mid);
arr = mergeSort(arr, mid + 1, right);
int[] temp = new int[right - left + 1];
int i = left;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {//判断左半边的数组还有没有剩
temp[k++] = arr[i++];
}
while (j <= right) {//判断右半边的数组还有没有剩
temp[k++] = arr[j++];
}
for (i = left, j = 0; i <= right; i++, j++) {//复制回自己的数组
arr[i] = temp[j];
}
return arr;
}
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] + " ");
}
}
}