Skip to content

Commit e233278

Browse files
authored
feat:Use generic for radixsort (#566)
1 parent ae98d52 commit e233278

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

sort/radixsort.go

+15-7
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1+
// radixsort.go
2+
// description: Implementation of in-place radixsort algorithm
3+
// details:
4+
// A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Radix_sort)
5+
16
package sort
27

3-
import "github.com/TheAlgorithms/Go/math/max"
8+
import (
9+
"github.com/TheAlgorithms/Go/constraints"
10+
"github.com/TheAlgorithms/Go/math/max"
11+
)
412

5-
func countSort(arr []int, exp int) []int {
13+
func countSort[T constraints.Integer](arr []T, exp T) []T {
614
var digits [10]int
7-
var output = make([]int, len(arr))
15+
var output = make([]T, len(arr))
816

917
for _, item := range arr {
1018
digits[(item/exp)%10]++
@@ -21,22 +29,22 @@ func countSort(arr []int, exp int) []int {
2129
return output
2230
}
2331

24-
func unsignedRadixSort(arr []int) []int {
32+
func unsignedRadixSort[T constraints.Integer](arr []T) []T {
2533
if len(arr) == 0 {
2634
return arr
2735
}
2836
maxElement := max.Int(arr...)
29-
for exp := 1; maxElement/exp > 0; exp *= 10 {
37+
for exp := T(1); maxElement/exp > 0; exp *= 10 {
3038
arr = countSort(arr, exp)
3139
}
3240
return arr
3341
}
3442

35-
func RadixSort(arr []int) []int {
43+
func RadixSort[T constraints.Integer](arr []T) []T {
3644
if len(arr) < 1 {
3745
return arr
3846
}
39-
var negatives, nonNegatives []int
47+
var negatives, nonNegatives []T
4048

4149
for _, item := range arr {
4250
if item < 0 {

sort/sorts_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ func TestShell(t *testing.T) {
112112
}
113113

114114
func TestRadix(t *testing.T) {
115-
testFramework(t, sort.RadixSort)
115+
testFramework(t, sort.RadixSort[int])
116116
}
117117

118118
func TestSimple(t *testing.T) {
@@ -217,7 +217,7 @@ func BenchmarkShell(b *testing.B) {
217217
}
218218

219219
func BenchmarkRadix(b *testing.B) {
220-
benchmarkFramework(b, sort.RadixSort)
220+
benchmarkFramework(b, sort.RadixSort[int])
221221
}
222222

223223
func BenchmarkSimple(b *testing.B) {

0 commit comments

Comments
 (0)