mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 16:06:27 +08:00
refactor(dart): Re-implement merge sort function (#896)
This commit is contained in:
parent
bd8cda325e
commit
1ab83bd3ef
1 changed files with 21 additions and 20 deletions
|
@ -5,28 +5,29 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* 合并左子数组和右子数组 */
|
/* 合并左子数组和右子数组 */
|
||||||
// 左子数组区间 [left, mid]
|
|
||||||
// 右子数组区间 [mid + 1, right]
|
|
||||||
void merge(List<int> nums, int left, int mid, int right) {
|
void merge(List<int> nums, int left, int mid, int right) {
|
||||||
// 初始化辅助数组
|
// 左子数组区间 [left, mid], 右子数组区间 [mid+1, right]
|
||||||
List<int> tmp = nums.sublist(left, right + 1);
|
// 创建一个临时数组 tmp ,用于存放合并后的结果
|
||||||
// 左子数组的起始索引和结束索引
|
List<int> tmp = List.filled(right - left + 1, 0);
|
||||||
int leftStart = left - left, leftEnd = mid - left;
|
// 初始化左子数组和右子数组的起始索引
|
||||||
// 右子数组的起始索引和结束索引
|
int i = left, j = mid + 1, k = 0;
|
||||||
int rightStart = mid + 1 - left, rightEnd = right - left;
|
// 当左右子数组都还有元素时,比较并将较小的元素复制到临时数组中
|
||||||
// i, j 分别指向左子数组、右子数组的首元素
|
while (i <= mid && j <= right) {
|
||||||
int i = leftStart, j = rightStart;
|
if (nums[i] <= nums[j])
|
||||||
// 通过覆盖原数组 nums 来合并左子数组和右子数组
|
tmp[k++] = nums[i++];
|
||||||
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
|
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];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue