forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pigeonholesort.go
44 lines (34 loc) · 939 Bytes
/
pigeonholesort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Pigeonhole algorithm's working at wikipedia.
// https://en.wikipedia.org/wiki/Pigeonhole_sort
// time complexity: O(n + N) where n is the number of elements in the array and N is the range of input
// space complexity: O(N)
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.
// 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
}
max := max.Int(arr...)
min := min.Int(arr...)
size := max - min + 1
holes := make([]T, size)
for _, element := range arr {
holes[element-min]++
}
i := 0
for j := T(0); j < size; j++ {
for holes[j] > 0 {
holes[j]--
arr[i] = j + min
i++
}
}
return arr
}