diff --git a/algorithm/sort.go b/algorithm/sort.go index ad2b6ad..847da1c 100644 --- a/algorithm/sort.go +++ b/algorithm/sort.go @@ -188,7 +188,8 @@ func CountSort[T any](slice []T, comparator constraints.Comparator) []T { count := 0 for j := 0; j < size; j++ { //slice[i] > slice[j] - if comparator.Compare(slice[i], slice[j]) == 1 { + order := comparator.Compare(slice[i], slice[j]) + if order == 1 || (order == 0 && j < i) { count++ } } diff --git a/algorithm/sort_test.go b/algorithm/sort_test.go index e96a5e6..49ab44d 100644 --- a/algorithm/sort_test.go +++ b/algorithm/sort_test.go @@ -199,6 +199,9 @@ func TestMergeSort(t *testing.T) { func TestCountSort(t *testing.T) { t.Parallel() assert := internal.NewAssert(t, "TestCountSort") + assert.Equal([]int{1, 2, 2}, CountSort([]int{2, 1, 2}, &intComparator{})) + assert.Equal([]people{{"young", 10}, {"first", 20}, {"second", 20}}, + CountSort([]people{{"first", 20}, {"young", 10}, {"second", 20}}, &peopleAgeComparator{})) peoples := []people{ {Name: "a", Age: 20},