Skip to content

Commit

Permalink
feat: Use generic for pigeonholesort and max min Int (#565)
Browse files Browse the repository at this point in the history
  • Loading branch information
VUHAILAM authored Oct 12, 2022
1 parent af1519c commit 44b39e0
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 7 deletions.
4 changes: 3 additions & 1 deletion math/max/max.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package max

import "github.com/TheAlgorithms/Go/constraints"

// Int is a function which returns the maximum of all the integers provided as arguments.
func Int(values ...int) int {
func Int[T constraints.Integer](values ...T) T {
max := values[0]
for _, value := range values {
if value > max {
Expand Down
4 changes: 3 additions & 1 deletion math/min/min.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package min

import "github.com/TheAlgorithms/Go/constraints"

// Int is a function which returns the minimum of all the integers provided as arguments.
func Int(values ...int) int {
func Int[T constraints.Integer](values ...T) T {
min := values[0]
for _, value := range values {
if value < min {
Expand Down
9 changes: 6 additions & 3 deletions sort/pigeonholesort.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
package sort

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

// Pigeonhole sorts a slice using pigeonhole sorting algorithm.
func Pigeonhole(arr []int) []int {
// NOTE: To maintain time complexity O(n + N), this is the reason for having
// only Integer constraint instead of Ordered.
func Pigeonhole[T constraints.Integer](arr []T) []T {
if len(arr) == 0 {
return arr
}
Expand All @@ -19,15 +22,15 @@ func Pigeonhole(arr []int) []int {

size := max - min + 1

holes := make([]int, size)
holes := make([]T, size)

for _, element := range arr {
holes[element-min]++
}

i := 0

for j := 0; j < size; j++ {
for j := T(0); j < size; j++ {
for holes[j] > 0 {
holes[j]--
arr[i] = j + min
Expand Down
4 changes: 2 additions & 2 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func TestComb(t *testing.T) {
}

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

func TestPatience(t *testing.T) {
Expand Down Expand Up @@ -238,7 +238,7 @@ func BenchmarkComb(b *testing.B) {
}

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

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

0 comments on commit 44b39e0

Please sign in to comment.