import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {1, 3, 5, 2, 4, 0, 1};
mergeSort(nums);
System.out.println(Arrays.toString(nums));
}
public static void mergeSort(int[] nums) {
sort(nums, 0, nums.length - 1);
}
//递归划分数组
public static void sort(int[] nums, int l, int r) {
if (l == r) return;
int mid = (l + r) / 2;
//数组划分
sort(nums, l, mid);
sort(nums, mid + 1, r);
merge(nums, l, mid, r);
}
//合并两个已经排好序的序列,一个从 l 开始到 mid,一个从 mid + 1 开始到 r
private static void merge(int[] nums, int l, int mid, int r) {
//暂存数组
int[] temp = nums.clone();
//记录两个序列各自起点
int i = l, j = mid + 1;
//遍历进行合并
for (int p = l; p <= r; p++) {
if (i == mid + 1) {
nums[p] = temp[j++];
} else if (j == r + 1) {
nums[p] = temp[i++];
} else if (temp[i] > temp[j]) {
nums[p] = temp[j++];
} else {
nums[p] = temp[i++];
}
}
}
}
归并排序算法Java版(易懂)
最新推荐文章于 2024-08-23 00:00:00 发布