利用归并排序的算法将读入的n个数从小到大排序后输出。java
时间: 2024-03-15 13:44:15 浏览: 135
好的,以下是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[] 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[nums.length];
int i = left;
int j = mid + 1;
int k = left;
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 = left; p <= right; p++) {
nums[p] = temp[p];
}
}
}
```
在这里,我们使用了归并排序的算法来进行排序。首先读入n个数,然后通过递归的方式进行排序。在归并的过程中,我们需要用到一个额外的数组来存储排序后的结果,最后再将结果拷贝回原数组。通过这种方式,我们可以将n个数从小到大排序后输出。
阅读全文