forked from krahets/hello-algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
8 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
|
@@ -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 { | ||
|
@@ -50,4 +48,4 @@ func mergeSort(nums []int, left, right int) { | |
mergeSort(nums, mid+1, right) | ||
// 合并阶段 | ||
merge(nums, left, mid, right) | ||
} | ||
} |