diff --git a/utils/utils_sort.go b/utils/utils_sort.go new file mode 100644 index 00000000..b8e6bf6e --- /dev/null +++ b/utils/utils_sort.go @@ -0,0 +1,23 @@ +package utils + +type SortItem struct { + CompareValue int64 + Index int +} + +type SortList []*SortItem + +func (p SortList) Len() int { + return len(p) +} + +// Less reports whether the element with +// index i should sort before the element with index j. +func (p SortList) Less(i, j int) bool { + return p[i].CompareValue < p[j].CompareValue +} + +// Swap swaps the elements with indexes i and j. +func (p SortList) Swap(i, j int) { + p[i], p[j] = p[j], p[i] +} diff --git a/utils/utils_sort_test.go b/utils/utils_sort_test.go new file mode 100644 index 00000000..2a65c09d --- /dev/null +++ b/utils/utils_sort_test.go @@ -0,0 +1,31 @@ +package utils + +import ( + "math/rand" + "sort" + "testing" +) + +func TestSort(t *testing.T) { + randIntList := make([]int, 100) + for k := range randIntList { + randIntList[k] = rand.Int() + } + copiedList := make([]int, len(randIntList)) + copy(copiedList, randIntList) + sort.Sort(sort.IntSlice(randIntList)) + + sortList := make(SortList, len(copiedList)) + for k := range copiedList { + sortList[k] = &SortItem{ + CompareValue: int64(copiedList[k]), + Index: k, + } + } + sort.Sort(sortList) + for k := range randIntList { + if randIntList[k] != copiedList[sortList[k].Index] { + t.Fatal("排序出错") + } + } +}