MergeSort.go
package main func MergeSort(items []int) []int { n := len(items) var combined []int switch { case n <= 1: combined = items case n == 2: if items[0] <= items[1] { combined = items } else { combined = append(combined, items[1], items[0]) } case n > 2: left := MergeSort(items[0 : n/2]) right := MergeSort(items[n/2:]) i := 0 j := 0 for i <= len(left) || j <= len(right) { switch { case left[i] == right[j]: combined = append(combined, left[i], right[j]) i++ j++ case left[i] < right[j]: combined = append(combined, left[i]) i++ case left[i] > right[j]: combined = append(combined, right[j]) j++ } if i == len(left) { combined = append(combined, right[j:]...) break } if j == len(right) { combined = append(combined, left[i:]...) break } } } return combined } func main() {}
MergeSort_test.go
package main import ( "reflect" "testing" ) func TestMergeSort(t *testing.T) { type TestCase struct { name string input []int expected []int } tests := []TestCase{ {"Case 1", []int{31, 27, 3, 54, 6, 9, 12, 8}, []int{3, 6, 8, 9, 12, 27, 31, 54}}, {"Case 2", []int{4, 3, 5, 3, 2, 2}, []int{2, 2, 3, 3, 4, 5}}, {"Case 3", []int{3, 5, 8, 4, 3}, []int{3, 3, 4, 5, 8}}, {"Case 4", []int{}, []int{}}, } for _, tc := range tests { sorted := MergeSort(tc.input) if !reflect.DeepEqual(sorted, tc.expected) { t.Errorf("%s failed. Input: %v Output: %v Expected: %v", tc.name, tc.input, sorted, tc.expected) } } }
标签:Sort,MergeSort,right,Case,int,Merge,combined,Go,tc From: https://www.cnblogs.com/zhangzhihui/p/17710012.html