用Java编码归并排序, 利用归并排序算法将读入的n个数从小到大排序后输出。
时间: 2023-07-07 10:38:43 浏览: 100
好的,下面是Java代码实现归并排序并对n个数进行排序:
```java
import java.util.Scanner;
public class MergeSort {
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] + " ");
}
}
private static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
private static void merge(int[] arr, int left, int mid, int right) {
int[] tmp = new int[right - left + 1];
int i = left, j = mid + 1, k = 0;
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 (int p = 0; p < tmp.length; p++) {
arr[left + p] = tmp[p];
}
}
}
```
代码中的mergeSort方法实现归并排序,merge方法实现归并操作。首先读入n个数,然后调用mergeSort方法进行排序,最后输出排好序的数组。
阅读全文