Skip to content

Commit

Permalink
Update merge_sort.go
Browse files Browse the repository at this point in the history
  • Loading branch information
krahets committed Dec 13, 2022
1 parent b8fb464 commit d2d7560
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions codes/go/chapter_sorting/merge_sort/merge_sort.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package merge_sort
// File: merge_sort.go
// Created Time: 2022-12-13
// Author: msk397 ([email protected])

/*
合并左子数组和右子数组
左子数组区间 [left, mid]
右子数组区间 [mid + 1, right]
*/
package merge_sort

// 合并左子数组和右子数组
// 左子数组区间 [left, mid]
// 右子数组区间 [mid + 1, right]
func merge(nums []int, left, mid, right int) {
// 初始化辅助数组 借助 copy模块
tmp := make([]int, right-left+1)
Expand All @@ -26,19 +25,18 @@ func merge(nums []int, left, mid, right int) {
if i > left_end {
nums[k] = tmp[j]
j++
// 否则,若 “右子数组已全部合并完” 或 “左子数组元素 < 右子数组元素”,则选取左子数组元素,并且 i++
// 否则,若 “右子数组已全部合并完” 或 “左子数组元素 < 右子数组元素”,则选取左子数组元素,并且 i++
} else if j > right_end || tmp[i] <= tmp[j] {
nums[k] = tmp[i]
i++
// 否则,若 “左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
// 否则,若 “左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
} else {
nums[k] = tmp[j]
j++
}
}
}


func mergeSort(nums []int, left, right int) {
// 终止条件
if left >= right {
Expand All @@ -50,4 +48,4 @@ func mergeSort(nums []int, left, right int) {
mergeSort(nums, mid+1, right)
// 合并阶段
merge(nums, left, mid, right)
}
}

0 comments on commit d2d7560

Please sign in to comment.