Skip to content

Commit

Permalink
feat:Use generic for radixsort (#566)
Browse files Browse the repository at this point in the history
  • Loading branch information
VUHAILAM authored Oct 13, 2022
1 parent ae98d52 commit e233278
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
22 changes: 15 additions & 7 deletions sort/radixsort.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
// radixsort.go
// description: Implementation of in-place radixsort algorithm
// details:
// A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Radix_sort)

package sort

import "github.com/TheAlgorithms/Go/math/max"
import (
"github.com/TheAlgorithms/Go/constraints"
"github.com/TheAlgorithms/Go/math/max"
)

func countSort(arr []int, exp int) []int {
func countSort[T constraints.Integer](arr []T, exp T) []T {
var digits [10]int
var output = make([]int, len(arr))
var output = make([]T, len(arr))

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

func unsignedRadixSort(arr []int) []int {
func unsignedRadixSort[T constraints.Integer](arr []T) []T {
if len(arr) == 0 {
return arr
}
maxElement := max.Int(arr...)
for exp := 1; maxElement/exp > 0; exp *= 10 {
for exp := T(1); maxElement/exp > 0; exp *= 10 {
arr = countSort(arr, exp)
}
return arr
}

func RadixSort(arr []int) []int {
func RadixSort[T constraints.Integer](arr []T) []T {
if len(arr) < 1 {
return arr
}
var negatives, nonNegatives []int
var negatives, nonNegatives []T

for _, item := range arr {
if item < 0 {
Expand Down
4 changes: 2 additions & 2 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func TestShell(t *testing.T) {
}

func TestRadix(t *testing.T) {
testFramework(t, sort.RadixSort)
testFramework(t, sort.RadixSort[int])
}

func TestSimple(t *testing.T) {
Expand Down Expand Up @@ -217,7 +217,7 @@ func BenchmarkShell(b *testing.B) {
}

func BenchmarkRadix(b *testing.B) {
benchmarkFramework(b, sort.RadixSort)
benchmarkFramework(b, sort.RadixSort[int])
}

func BenchmarkSimple(b *testing.B) {
Expand Down

0 comments on commit e233278

Please sign in to comment.