携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情
归并排序
归并排序是建立在归并操作的排序算法, 是分治法的典型应用. 将已有序的子序列合并, 得到完全有序的序列; 即先使每个子序列有序, 再使子序列段间有序. 若将两个有序表合成一个有序表, 称为2-路归并
1.1 算法描述
-
递归法
- 申请空间使其大小为两个已排序序列之和, 该空间用来存放合并后的序列
- 设定两个指针, 最初位置分别为两个已排序序列起始位置
- 比较两个指针所指向的元素, 选择相对小的元素放入到合并空间, 并移动指针到下一位置
- 重复步骤3直到某一指针达到序列尾部
- 将另一序列剩下的所有元素直接复制到合并序列尾部
1.3 演示
1.3 代码实现
/**
* 递归法归并
*
* @param nums 数组
*/
public int[] recursionMergeSort(int[] nums) {
int length = nums.length;
if (length < 2) {
return nums;
}
int middle = length / 2;
int[] left = new int[middle];
int[] right = new int[middle];
// 数组折半分组
System.arraycopy(nums, 0, left, 0, middle);
System.arraycopy(nums, middle, right, 0, length - middle);
return merge(recursionMergeSort(left), recursionMergeSort(right));
}
private int[] merge(int[] left, int[] right) {
int resIndex = 0;
int[] res = new int[left.length + right.length];
int leftIndex = 0, rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
res[resIndex] = left[leftIndex++];
} else {
res[resIndex] = right[rightIndex++];
}
resIndex++;
}
while (leftIndex < left.length) {
res[resIndex ++] = left[leftIndex++];
}
while (rightIndex < right.length) {
res[resIndex ++] = right[rightIndex++];
}
return res;
}