|
|
@ -7,33 +7,34 @@
|
|
|
|
#include "../utils/common.h"
|
|
|
|
#include "../utils/common.h"
|
|
|
|
|
|
|
|
|
|
|
|
/* 合并左子数组和右子数组 */
|
|
|
|
/* 合并左子数组和右子数组 */
|
|
|
|
// 左子数组区间 [left, mid]
|
|
|
|
|
|
|
|
// 右子数组区间 [mid + 1, right]
|
|
|
|
|
|
|
|
void merge(int *nums, int left, int mid, int right) {
|
|
|
|
void merge(int *nums, int left, int mid, int right) {
|
|
|
|
int index;
|
|
|
|
// 左子数组区间 [left, mid], 右子数组区间 [mid+1, right]
|
|
|
|
// 初始化辅助数组
|
|
|
|
// 创建一个临时数组 tmp ,用于存放合并后的结果
|
|
|
|
int tmp[right + 1 - left];
|
|
|
|
int tmpSize = right - left + 1;
|
|
|
|
for (index = left; index < right + 1; index++) {
|
|
|
|
int *tmp = (int *)malloc(tmpSize * sizeof(int));
|
|
|
|
tmp[index - left] = nums[index];
|
|
|
|
// 初始化左子数组和右子数组的起始索引
|
|
|
|
|
|
|
|
int i = left, j = mid + 1, k = 0;
|
|
|
|
|
|
|
|
// 当左右子数组都还有元素时,比较并将较小的元素复制到临时数组中
|
|
|
|
|
|
|
|
while (i <= mid && j <= right) {
|
|
|
|
|
|
|
|
if (nums[i] <= nums[j]) {
|
|
|
|
|
|
|
|
tmp[k++] = nums[i++];
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
tmp[k++] = nums[j++];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// 左子数组的起始索引和结束索引
|
|
|
|
|
|
|
|
int leftStart = left - left, leftEnd = mid - left;
|
|
|
|
|
|
|
|
// 右子数组的起始索引和结束索引
|
|
|
|
|
|
|
|
int rightStart = mid + 1 - left, rightEnd = right - left;
|
|
|
|
|
|
|
|
// i, j 分别指向左子数组、右子数组的首元素
|
|
|
|
|
|
|
|
int i = leftStart, j = rightStart;
|
|
|
|
|
|
|
|
// 通过覆盖原数组 nums 来合并左子数组和右子数组
|
|
|
|
|
|
|
|
for (int k = left; k <= right; k++) {
|
|
|
|
|
|
|
|
// 若“左子数组已全部合并完”,则选取右子数组元素,并且 j++
|
|
|
|
|
|
|
|
if (i > leftEnd)
|
|
|
|
|
|
|
|
nums[k] = tmp[j++];
|
|
|
|
|
|
|
|
// 否则,若“右子数组已全部合并完”或“左子数组元素 <= 右子数组元素”,则选取左子数组元素,并且 i++
|
|
|
|
|
|
|
|
else if (j > rightEnd || tmp[i] <= tmp[j])
|
|
|
|
|
|
|
|
nums[k] = tmp[i++];
|
|
|
|
|
|
|
|
// 否则,若“左右子数组都未全部合并完”且“左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
|
|
|
|
|
|
|
|
else
|
|
|
|
|
|
|
|
nums[k] = tmp[j++];
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 将左子数组和右子数组的剩余元素复制到临时数组中
|
|
|
|
|
|
|
|
while (i <= mid) {
|
|
|
|
|
|
|
|
tmp[k++] = nums[i++];
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
while (j <= right) {
|
|
|
|
|
|
|
|
tmp[k++] = nums[j++];
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// 将临时数组 tmp 中的元素复制回原数组 nums 的对应区间
|
|
|
|
|
|
|
|
for (k = 0; k < tmpSize; ++k) {
|
|
|
|
|
|
|
|
nums[left + k] = tmp[k];
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// 释放内存
|
|
|
|
|
|
|
|
free(tmp);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* 归并排序 */
|
|
|
|
/* 归并排序 */
|
|
|
|