From 1ab83bd3efdd2294c13531953983a08404b9dcaf Mon Sep 17 00:00:00 2001 From: liuyuxin Date: Fri, 27 Oct 2023 16:00:26 +0800 Subject: [PATCH] refactor(dart): Re-implement merge sort function (#896) --- codes/dart/chapter_sorting/merge_sort.dart | 41 +++++++++++----------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/codes/dart/chapter_sorting/merge_sort.dart b/codes/dart/chapter_sorting/merge_sort.dart index a08ff5feb..b31ca68ca 100644 --- a/codes/dart/chapter_sorting/merge_sort.dart +++ b/codes/dart/chapter_sorting/merge_sort.dart @@ -5,28 +5,29 @@ */ /* 合并左子数组和右子数组 */ -// 左子数组区间 [left, mid] -// 右子数组区间 [mid + 1, right] void merge(List nums, int left, int mid, int right) { - // 初始化辅助数组 - List tmp = nums.sublist(left, right + 1); - // 左子数组的起始索引和结束索引 - 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++ + // 左子数组区间 [left, mid], 右子数组区间 [mid+1, right] + // 创建一个临时数组 tmp ,用于存放合并后的结果 + List tmp = List.filled(right - left + 1, 0); + // 初始化左子数组和右子数组的起始索引 + int i = left, j = mid + 1, k = 0; + // 当左右子数组都还有元素时,比较并将较小的元素复制到临时数组中 + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) + tmp[k++] = nums[i++]; else - nums[k] = tmp[j++]; + tmp[k++] = nums[j++]; + } + // 将左子数组和右子数组的剩余元素复制到临时数组中 + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= right) { + tmp[k++] = nums[j++]; + } + // 将临时数组 tmp 中的元素复制回原数组 nums 的对应区间 + for (k = 0; k < tmp.length; k++) { + nums[left + k] = tmp[k]; } }