Skip to content

Commit f12023b

Browse files
committed
init Radix
1 parent f009f67 commit f12023b

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

sorts/Radix.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"strconv"
6+
)
7+
8+
// Finds the largest number in an array
9+
func findLargestNum(array []int) int {
10+
largestNum := 0
11+
12+
for i := 0; i < len(array); i++ {
13+
if array[i] > largestNum {
14+
largestNum = array[i]
15+
}
16+
}
17+
return largestNum
18+
}
19+
20+
// Radix Sort
21+
func radixSort(array []int) []int {
22+
23+
fmt.Println("Running Radix Sort on Unsorted List\n")
24+
25+
// Base 10 is used
26+
largestNum := findLargestNum(array)
27+
size := len(array)
28+
significantDigit := 1
29+
semiSorted := make([]int, size, size)
30+
31+
// Loop until we reach the largest significant digit
32+
for largestNum/significantDigit > 0 {
33+
34+
fmt.Println("\tSorting: "+strconv.Itoa(significantDigit)+"'s place", array)
35+
36+
bucket := [10]int{0}
37+
38+
// Counts the number of "keys" or digits that will go into each bucket
39+
for i := 0; i < size; i++ {
40+
bucket[(array[i]/significantDigit)%10]++
41+
}
42+
43+
// Add the count of the previous buckets
44+
// Acquires the indexes after the end of each bucket location in the array
45+
// Works similar to the count sort algorithm
46+
for i := 1; i < 10; i++ {
47+
bucket[i] += bucket[i-1]
48+
}
49+
50+
// Use the bucket to fill a "semiSorted" array
51+
for i := size - 1; i >= 0; i-- {
52+
bucket[(array[i]/significantDigit)%10]--
53+
semiSorted[bucket[(array[i]/significantDigit)%10]] = array[i]
54+
}
55+
56+
// Replace the current array with the semisorted array
57+
for i := 0; i < size; i++ {
58+
array[i] = semiSorted[i]
59+
}
60+
61+
fmt.Println("\tBucket: ", bucket, "\n")
62+
63+
// Move to next significant digit
64+
significantDigit *= 10
65+
}
66+
67+
return array
68+
}
69+
70+
func main() {
71+
72+
fmt.Println("\n\nRunning Radix Sort")
73+
fmt.Println("------------------\n")
74+
75+
unsortedList := []int{10, 2, 303, 4021, 293, 1, 0, 429, 480, 92, 2999, 14}
76+
fmt.Println("Unsorted List:", unsortedList, "\n")
77+
78+
sortedList := radixSort(unsortedList)
79+
80+
fmt.Println("\nSorted List:", sortedList, "\n")
81+
}

0 commit comments

Comments
 (0)