利用归并排序算法将读入的 n 个数从小到大排序后输出。JAVA
时间: 2023-07-07 21:34:05 浏览: 65
java实现归并排序算法
好的,下面是 Java 代码实现归并排序算法:
```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[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
mergeSort(nums, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(nums[i] + " ");
}
}
private static void mergeSort(int[] nums, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right);
}
}
private static void merge(int[] nums, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) {
temp[k++] = nums[i++];
} else {
temp[k++] = nums[j++];
}
}
while (i <= mid) {
temp[k++] = nums[i++];
}
while (j <= right) {
temp[k++] = nums[j++];
}
for (int p = 0; p < temp.length; p++) {
nums[left + p] = temp[p];
}
}
}
```
以上代码将读入的 n 个数存入数组 nums 中,然后调用 `mergeSort` 方法进行归并排序,最后输出排序后的结果即可。
阅读全文