Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:Use generic for radixsort #566

Merged
merged 4 commits into from
Oct 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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