归并排序
图片来源:https://www.runoob.com/w3cnote/merge-sort.html
package com.miracle.study.sort;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
/**
* @author Miracle
* @date 2021/4/6 17:20
*/
public class MergeSort {
public int[] mergeSort(int[] sortData, int left, int right){
// 判断是否可以再分
if (right - left <= 1){
return new int[]{Integer.MAX_VALUE};
}
// 计算中间值
var mid = (left + right) / 2;
// 分解
mergeSort(sortData, left, mid);
mergeSort(sortData, mid, right);
// 比较与合并
return merge(sortData, left, right, mid);
}
private int[] merge(int[] sortData, int left, int right, int mid) {
// 获取两段的数组
var leftSort = Arrays.copyOfRange(sortData, left, mid + 1);
var rightSort = Arrays.copyOfRange(sortData, mid, right + 1);
// 设置哨兵,避免循环时越界
leftSort[leftSort.length - 1] = Integer.MAX_VALUE;
rightSort[rightSort.length - 1] = Integer.MAX_VALUE;
int i = 0 ,j = 0;
// 核心逻辑,k值直接作为原数组的下标来置换提取的数组数据。
for (int k = left; k < right; k++){
if (leftSort[i] < rightSort[j]){
sortData[k] = leftSort[i++];
}else {
sortData[k] = rightSort[j++];
}
}
return sortData;
}
@Test
public void sort(){
var a = new int[]{1,5,7,9,3,6,8,4,2,10,0,19};
int[] ints = mergeSort(a, 0, a.length - 1);
Arrays.stream(ints).forEach(e -> System.out.println(e));
}
}