Skip to content

Commit 76bcf08

Browse files
authored
feat: Add Radix sort. (#8)
1 parent 0472c51 commit 76bcf08

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ So far, the following exercises have been covered:
99
- [Autocomplete](./autocomplete/) – implements an autocomplete feature using a trie
1010
- [Continous maximum](./continuousmax/) – calculates the maximum of a sliding window
1111
- [Heap](./heap/) – implements a heap from scratch, without using the built-in `container/heap` package
12+
- [Radix sort](./radixsort/) – implements radix sort
1213
- [Remove k-th last element](./removekthlastelement/) – removes the k-th last element from a single-linked list
1314
- [Running median](./runningmedian/) – calculates the running median of a sequence of numbers
1415
- [Tic tac toe](./tictactoe/) – detects winnning states in a tic tac toe game

radixsort/documentation.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// Package radixsort implements radix sort.
2+
package radixsort

radixsort/radix_sort.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package radixsort
2+
3+
import (
4+
"math"
5+
)
6+
7+
func max(values []int) int {
8+
maxValue := math.MinInt
9+
for _, value := range values {
10+
if value > maxValue {
11+
maxValue = value
12+
}
13+
}
14+
return maxValue
15+
}
16+
17+
func countDigits(number int) int {
18+
if number == 0 {
19+
return 1
20+
}
21+
return int(math.Log10(float64(number))) + 1
22+
}
23+
24+
func getDigit(number, n int) int {
25+
return (number / int(math.Pow(10, float64(n)))) % 10
26+
}
27+
28+
func Sort(values []int) []int {
29+
digits := countDigits(max(values))
30+
31+
for k := 0; k < digits; k++ {
32+
buckets := make([][]int, 10)
33+
34+
for _, value := range values {
35+
digit := getDigit(value, k)
36+
buckets[digit] = append(buckets[digit], value)
37+
}
38+
39+
values = []int{}
40+
for _, bucket := range buckets {
41+
values = append(values, bucket...)
42+
}
43+
}
44+
45+
return values
46+
}

radixsort/radix_sort_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package radixsort_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
"github.com/thenativeweb/codingcircle/radixsort"
8+
)
9+
10+
func TestSort(t *testing.T) {
11+
unsorted := []int{12, 27, 2, 17, 9, 8}
12+
sorted := []int{2, 8, 9, 12, 17, 27}
13+
14+
assert.Equal(t, sorted, radixsort.Sort(unsorted))
15+
}

0 commit comments

Comments
 (0)