归并排序主要两步,一步是划分区间,另一步是合并两个区间
这个算法的稳定性更好,对比快排这种,如果整体是倒序的话,快排的复杂度会达到o(n^2),归并会更稳定。
划分区间主要是递归去实现,下面给出代码
package com.codeking.sortTest;/*** @author xiongjl* @since 2023/10/31 13:19*/
public class sortTest {public static void main(String[] args) {int[] arr = {1, 2, 5, 4, 9, 8, 7};mergeSort(arr, new int[arr.length], 0, arr.length - 1);for (int i = 0; i < arr.length; i++) {System.out.print(arr[i]);}}// 归并排序static void mergeSort(int[] arr, int[] temp, int left, int right) {// 如果left和right相等,说明只有以一个元素if (left < right) {int mid = left + (right - left) / 2;// 处理左右区间mergeSort(arr, temp, left, mid);mergeSort(arr, temp, mid + 1, right);// 合并区间merge(arr, temp, left, mid, right);}}// 合并有序数组 [5,4,2,6]static void merge(int[] arr, int[] temp, int left, int mid, int right) {int leftPos = left, rightPos = mid + 1, pos = left;// 两边都有元素while (leftPos <= mid && rightPos <= right) {if (arr[leftPos] < arr[rightPos]) {temp[pos++] = arr[leftPos++];} else {temp[pos++] = arr[rightPos++];}}// 处理剩下的元素while (leftPos <= mid) {temp[pos++] = arr[leftPos++];}while (rightPos <= right) {temp[pos++] = arr[rightPos++];}// 覆盖原数组while (left <= right) {arr[left] = temp[left];left++;}}
}
有一个讲排序算法挺不错的up主,可以看看:排序算法:归并排序【图解+代码】_哔哩哔哩_bilibili