java二分归并排序算法
时间: 2023-10-29 11:54:05 浏览: 115
二分插入排序算法
Java中的二分归并排序算法是一种基于分治思想的排序算法。它将待排序序列不断地二分,并对两个子序列分别进行递归排序,最后通过合并两个有序序列来完成排序。这个算法的实现可以参考以下代码:
```java
package sort;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = { 8, 4, 5, 7, 1, 3, 6, 2 };
int[] temp = new int[arr.length]; // 辅助数组
mergeSort(arr, temp, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void mergeSort(int[] arr, int[] temp, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(arr, temp, low, mid); // 1. 对左边进行归并排序
mergeSort(arr, temp, mid + 1, high); // 2. 对右边进行归并排序
merge(arr, temp, low, mid, high); // 3. 合并左右两个有序集合
}
}
public static void merge(int[] arr, int[] temp, int low, int mid, int high) {
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= high) {
if (arr[i <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) { // 左边有剩余,将左边剩余的填入temp
temp[k++] = arr[i++];
}
while (j <= high) { // 右边有剩余,将右边剩余的填入temp
temp[k++] = arr[j++];
}
k = 0;
while (low <= high) {
arr<span class="em">1</span><span class="em">2</span><span class="em">3</span>
阅读全文