1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add CountSort

This commit is contained in:
dudaodong
2022-01-16 17:20:20 +08:00
parent 98e861cf3b
commit e6f9b0954c
2 changed files with 34 additions and 2 deletions

View File

@@ -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]

View File

@@ -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)
}