diff --git a/algorithm/sorter.go b/algorithm/sorter.go index 66cf557..81b14e4 100644 --- a/algorithm/sorter.go +++ b/algorithm/sorter.go @@ -1,7 +1,7 @@ // Copyright 2021 dudaodong@gmail.com. All rights reserved. // Use of this source code is governed by MIT license -// Package algorithm contain some algorithm functions. eg. sort, find, list, linklist, stack, queue, tree, graph. TODO +// Package algorithm contain some basic algorithm functions. eg. sort, search, list, linklist, stack, queue, tree, graph. TODO package algorithm import "github.com/duke-git/lancet/lancetconstraints" @@ -183,6 +183,25 @@ func merge[T any](slice []T, low, mid, high int, comparator lancetconstraints.Co } } +// CountSort use count sorting for slice +func CountSort[T any](slice []T, comparator lancetconstraints.Comparator) []T { + size := len(slice) + out := make([]T, size) + + for i := 0; i < size; i++ { + count := 0 + for j := 0; j < size; j++ { + //slice[i] > slice[j] + if comparator.Compare(slice[i], slice[j]) == 1 { + count++ + } + } + out[count] = slice[i] + } + + return out +} + // swap two slice value at index i and j func swap[T any](slice []T, i, j int) { slice[i], slice[j] = slice[j], slice[i] diff --git a/algorithm/sorter_test.go b/algorithm/sorter_test.go index 79b75d3..8acd7ae 100644 --- a/algorithm/sorter_test.go +++ b/algorithm/sorter_test.go @@ -151,7 +151,7 @@ func TestHeapSort(t *testing.T) { } func TestMergeSort(t *testing.T) { - asssert := internal.NewAssert(t, "TestHeapSort") + asssert := internal.NewAssert(t, "TestMergeSort") comparator := &peopleAageComparator{} sortedPeopleByAge := MergeSort(peoples, 0, len(peoples)-1, comparator) @@ -160,5 +160,18 @@ func TestMergeSort(t *testing.T) { expected := "[{d 8} {b 10} {c 17} {a 20} {e 28}]" actual := fmt.Sprintf("%v", sortedPeopleByAge) + asssert.Equal(expected, actual) +} + +func TestCountSort(t *testing.T) { + asssert := internal.NewAssert(t, "TestCountSort") + + comparator := &peopleAageComparator{} + sortedPeopleByAge := CountSort(peoples, comparator) + t.Log(sortedPeopleByAge) + + expected := "[{d 8} {b 10} {c 17} {a 20} {e 28}]" + actual := fmt.Sprintf("%v", sortedPeopleByAge) + asssert.Equal(expected, actual) } \ No newline at end of file