做法
將陣列分割後排序,再將兩個已排序的陣列合併成一個陣列。
實作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| func MergeSort(items []int) []int { if len(items) <= 1 { return items }
half := len(items) / 2 left := MergeSort(items[:half]) right := MergeSort(items[half:])
result := []int{}
for len(left) > 0 && len(right) > 0 { if left[0] < right[0] { item := left[0] left = left[1:] result = append(result, item) } else { item := right[0] right = right[1:] result = append(result, item) } }
result = append(result, left...) result = append(result, right...)
return result }
|
程式碼