Skip to content

Commit 44b39e0

Browse files
authored
feat: Use generic for pigeonholesort and max min Int (#565)
1 parent af1519c commit 44b39e0

File tree

4 files changed

+14
-7
lines changed

4 files changed

+14
-7
lines changed

math/max/max.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package max
22

3+
import "github.com/TheAlgorithms/Go/constraints"
4+
35
// Int is a function which returns the maximum of all the integers provided as arguments.
4-
func Int(values ...int) int {
6+
func Int[T constraints.Integer](values ...T) T {
57
max := values[0]
68
for _, value := range values {
79
if value > max {

math/min/min.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package min
22

3+
import "github.com/TheAlgorithms/Go/constraints"
4+
35
// Int is a function which returns the minimum of all the integers provided as arguments.
4-
func Int(values ...int) int {
6+
func Int[T constraints.Integer](values ...T) T {
57
min := values[0]
68
for _, value := range values {
79
if value < min {

sort/pigeonholesort.go

+6-3
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@
44
package sort
55

66
import (
7+
"github.com/TheAlgorithms/Go/constraints"
78
"github.com/TheAlgorithms/Go/math/max"
89
"github.com/TheAlgorithms/Go/math/min"
910
)
1011

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

2023
size := max - min + 1
2124

22-
holes := make([]int, size)
25+
holes := make([]T, size)
2326

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

2831
i := 0
2932

30-
for j := 0; j < size; j++ {
33+
for j := T(0); j < size; j++ {
3134
for holes[j] > 0 {
3235
holes[j]--
3336
arr[i] = j + min

sort/sorts_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ func TestComb(t *testing.T) {
132132
}
133133

134134
func TestPigeonhole(t *testing.T) {
135-
testFramework(t, sort.Pigeonhole)
135+
testFramework(t, sort.Pigeonhole[int])
136136
}
137137

138138
func TestPatience(t *testing.T) {
@@ -238,7 +238,7 @@ func BenchmarkComb(b *testing.B) {
238238
}
239239

240240
func BenchmarkPigeonhole(b *testing.B) {
241-
benchmarkFramework(b, sort.Pigeonhole)
241+
benchmarkFramework(b, sort.Pigeonhole[int])
242242
}
243243

244244
func BenchmarkPatience(b *testing.B) {

0 commit comments

Comments
 (0)