Skip to content

Commit

Permalink
refactor: merge
Browse files Browse the repository at this point in the history
  • Loading branch information
nuomi1 committed Oct 27, 2023
1 parent 6af02b1 commit f85a709
Showing 1 changed file with 28 additions and 27 deletions.
55 changes: 28 additions & 27 deletions codes/swift/chapter_sorting/merge_sort.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,39 @@
*/

/* 合并左子数组和右子数组 */
// 左子数组区间 [left, mid]
// 右子数组区间 [mid + 1, right]
func merge(nums: inout [Int], left: Int, mid: Int, right: Int) {
// 初始化辅助数组
let tmp = Array(nums[left ..< (right + 1)])
// 左子数组的起始索引和结束索引
let leftStart = left - left
let leftEnd = mid - left
// 右子数组的起始索引和结束索引
let rightStart = mid + 1 - left
let rightEnd = right - left
// i, j 分别指向左子数组、右子数组的首元素
var i = leftStart
var j = rightStart
// 通过覆盖原数组 nums 来合并左子数组和右子数组
for k in left ... right {
// 若“左子数组已全部合并完”,则选取右子数组元素,并且 j++
if i > leftEnd {
nums[k] = tmp[j]
j += 1
}
// 否则,若“右子数组已全部合并完”或“左子数组元素 <= 右子数组元素”,则选取左子数组元素,并且 i++
else if j > rightEnd || tmp[i] <= tmp[j] {
nums[k] = tmp[i]
// 左子数组区间 [left, mid], 右子数组区间 [mid+1, right]
// 创建一个临时数组 tmp ,用于存放合并后的结果
var tmp = Array(repeating: 0, count: right - left + 1)
// 初始化左子数组和右子数组的起始索引
var i = left, j = mid + 1, k = 0
// 当左右子数组都还有元素时,比较并将较小的元素复制到临时数组中
while i <= mid, j <= right {
if nums[i] <= nums[j] {
tmp[k] = nums[i]
i += 1
}
// 否则,若“左右子数组都未全部合并完”且“左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
else {
nums[k] = tmp[j]
k += 1
} else {
tmp[k] = nums[j]
j += 1
k += 1
}
}
// 将左子数组和右子数组的剩余元素复制到临时数组中
while i <= mid {
tmp[k] = nums[i]
i += 1
k += 1
}
while j <= right {
tmp[k] = nums[j]
j += 1
k += 1
}
// 将临时数组 tmp 中的元素复制回原数组 nums 的对应区间
for k in tmp.indices {
nums[left + k] = tmp[k]
}
}

/* 归并排序 */
Expand Down

0 comments on commit f85a709

Please sign in to comment.