写个java的归并排序
时间: 2023-09-10 18:10:43 浏览: 48
以下是Java中的归并排序实现:
```java
public class MergeSort {
public static void mergeSort(int[] array) {
if (array == null || array.length == 0) {
return;
}
int[] temp = new int[array.length];
mergeSort(array, temp, 0, array.length - 1);
}
private static void mergeSort(int[] array, int[] temp, int left, int right) {
if (left >= right) {
return;
}
int mid = (left + right) / 2;
mergeSort(array, temp, left, mid);
mergeSort(array, temp, mid + 1, right);
merge(array, temp, left, mid, right);
}
private static void merge(int[] array, int[] temp, int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = left;
while (i <= mid && j <= right) {
if (array[i] <= array[j]) {
temp[k++] = array[i++];
} else {
temp[k++] = array[j++];
}
}
while (i <= mid) {
temp[k++] = array[i++];
}
while (j <= right) {
temp[k++] = array[j++];
}
for (int m = left; m <= right; m++) {
array[m] = temp[m];
}
}
}
```
归并排序的主要思想是将一个数组分成两个子数组,分别对子数组进行排序,然后将两个子数组合并成一个有序数组。在Java中,我们可以使用递归来完成这个过程。
首先,我们需要定义一个 `mergeSort` 方法,该方法将调用另一个 `mergeSort` 方法来进行递归排序。在 `mergeSort` 方法中,我们需要定义一个 `temp` 数组,用于合并两个有序子数组。然后,我们将数组分成两个子数组,分别调用 `mergeSort` 方法对它们进行排序。最后,我们将两个子数组合并成一个有序数组。
在 `merge` 方法中,我们定义了三个指针 `i`、`j` 和 `k`,用于遍历两个有序子数组和 `temp` 数组。我们比较两个子数组中的元素,将较小的元素依次放入 `temp` 数组中。最后,我们将 `temp` 数组中的元素复制回原数组中。
归并排序的时间复杂度为 O(nlogn),空间复杂度为 O(n)。由于归并排序是一种稳定的排序算法,因此在一些特殊的排序场景中比较实用。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)