利用归并排序算法将读入的n个数从小到大排序后输出。本题为函数题,只需要提交函数即可。 java
时间: 2024-03-15 18:46:13 浏览: 72
以下是Java实现归并排序的代码:
```java
public static void mergeSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
public static void merge(int[] arr, 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 (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 (int p = 0; p < temp.length; p++) {
arr[left + p] = temp[p];
}
}
```
在主函数中调用该方法即可进行归并排序,示例代码如下:
```java
public static void main(String[] args) {
int[] arr = {5, 3, 8, 6, 2, 7, 1, 4};
mergeSort(arr, 0, arr.length - 1);
for (int i : arr) {
System.out.print(i + " ");
}
}
```
输出结果为:1 2 3 4 5 6 7 8
阅读全文