File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -136,6 +136,48 @@ func merge(left []int, right []int) []int {
136136 return result
137137}
138138```
139+ // 改进
140+
141+ ``` go
142+ // 归并排序函数
143+ func mergeSort (arr []int ) []int {
144+ // 如果数组长度小于等于 1,直接返回
145+ if len (arr) <= 1 {
146+ return arr
147+ }
148+
149+ // 分割数组
150+ mid := len (arr) / 2
151+ left := mergeSort (arr[:mid])
152+ right := mergeSort (arr[mid:])
153+
154+ // 合并两个有序数组
155+ return merge (left, right)
156+ }
157+
158+ // 合并两个有序数组
159+ func merge (left , right []int ) []int {
160+ // 初始化结果数组,预留足够的容量
161+ result := make ([]int , 0 , len (left)+len (right))
162+ i , j := 0 , 0
163+
164+ // 比较两个数组的元素,将较小的元素加入结果数组
165+ for i < len (left) && j < len (right) {
166+ if left[i] <= right[j] {
167+ result = append (result, left[i])
168+ i++
169+ } else {
170+ result = append (result, right[j])
171+ j++
172+ }
173+ }
174+
175+ // 将剩余的元素加入结果数组
176+ result = append (result, left[i:]...)
177+ result = append (result, right[j:]...)
178+ return result
179+ }
180+ ```
139181
140182## 7. Java 代码实现
141183
You can’t perform that action at this time.
0 commit comments