# Golang program to implement radix sort using counting sort as a subroutine

Radix sort is an algorithm that sorts elements from their digits. It has a linear time complexity and is used for sorting large amounts of data. It uses counting sort to calculate the frequencies of digits.

Counting Sort is an algorithm that is efficient in sorting when the input is integer within a particular range. It counts the occurrence of each unique element from the input and uses that information to get the correct position of each element.

A subroutine is a function of the program which performs a specific task and can be used when and repeatedly called in the program where its needed.

## Syntax

func len(v Type) int


The len() method returns the length of any parameter. It accepts one input, the data type variable whose length we want to know, and returns the integer value that is the variable's length.

func make ([] type, size, capacity)


The make function in Go is used to build an array/map. It receives as arguments the kind of variable to be generated, as well as its size and capacity.

func range(variable)


The range function iterates through any data type. To utilize this, we must first put the range keyword, followed by the data type to which we want to iterate, and the loop will iterate until the final element of the variable is reached.

## Algorithm

• Step 1 − This program imports fmt, main and math as necessary packages

• Step 2 − Create a function named find_max to find the maximum element in the array

• Step 3 − For every digit use counting sort algorithm beginning from the least significant digit to the most significant digit

• Step 4 − Now Create a counting array of integers with a size of 10 and set the count array with all zeros.

• Step 5 − Update the count array to store the cumulative count of each digit. This shows the starting position of each digit in the output array

• Step 6 − Then, traverse the input array in reverse order and place each element in its correct position in the output array based on the current digit

• Step 7 − place the output array back to the input array, increment exp by a factor of 10 with each iteration and After all the iterations, the input array will be sorted in a non-decreasing order

## Example 1 : Using Repetition

In this example, we will write a Go language program to implement radix sort using count sort as a subroutine where counting sort counts each digit and radix sort calls the count sort repeatedly to sort the array.

package main

import (
"fmt"
"math"
)

func findmaximum(array []int) int {
maximum := math.MinInt64
for _, number := range array {
if number > maximum {
maximum = number
}
}
return maximum
}

func countsort(array []int, exp int) {
m := len(array)
output := make([]int, m)
count := make([]int, 10)

for a := 0; a < 10; a++ {
count[a] = 0
}

for a := 0; a < m; a++ {
index := (array[a] / exp) % 10
count[index]++
}

for a := 1; a < 10; a++ {
count[a] += count[a-1]
}

for a := m - 1; a >= 0; a-- {
index := (array[a] / exp) % 10
output[count[index]-1] = array[a]
count[index]--
}

for a := 0; a < m; a++ {
array[a] = output[a]
}
}

maximum := findmaximum(array)

for exp := 1; maximum/exp > 0; exp *= 10 {
countsort(array, exp)
}
}

func main() {
array := []int{10, 12, 18, 02, 04, 95, 72, 62}
fmt.Println("The Unsorted array is:", array)
fmt.Println("After sorting:", array)
}


## Output

Original aray is :  [10 12 18 2 4 95 72 62]
The Sorted array: [2 4 10 12 18 62 72 95]


## Example 2: Iterative Implementation with queue

In this example, we will write a Go language program to implement radix sort using count sort as a subroutine that involves the processing of each digit from LSD to the MSD.

package main

import (
"fmt"
)

type Queue struct {
elements []int
}

func (q *Queue) Enqueue(element int) {
q.elements = append(q.elements, element)
}

func (q *Queue) Dequeue() int {
element := q.elements
q.elements = q.elements[1:]
return element
}

func (q *Queue) IsEmpty() bool {
return len(q.elements) == 0
}

func getmaximum(arr []int) int {
max := arr
for _, num := range arr {
if num > max {
max = num
}
}
return max
}

max := getmaximum(arr)
digits := 0
for max > 0 {
max /= 10
digits++
}

for i := 0; i < digits; i++ {
queues := make([]*Queue, 10)
for j := 0; j < 10; j++ {
queues[j] = &Queue{elements: []int{}}
}

for _, num := range arr {
digit := (num / Pow(10, i)) % 10
queues[digit].Enqueue(num)
}

index := 0
for j := 0; j < 10; j++ {
for !queues[j].IsEmpty() {
arr[index] = queues[j].Dequeue()
index++
}
}
}

return arr
}

func Pow(base, exp int) int {
result := 1
for exp > 0 {
if exp&1 != 0 {
result *= base
}
base *= base
exp >>= 1
}
return result
}

func main() {
arr := []int{110, 223, 45, 50, 812, 84, 21, 17}
fmt.Println("Array after sorting:", sorted)
}


## Output

Array after sorting : [17 21 45 50 84 110 223 812]


### Example 3: In pace Radix Sort

In this example, we will write a Go language program to implement radix sort using count sort as a subroutine. In this method sorting is done in-place which means that it does not require extra spaces proportional to the input.

package main

import (
"fmt"
)

func getMax(array []int) int {
max := array
for _, num := range array {
if num > max {
max = num
}
}
return max
}

func countingSort(array []int, exp int) {
n := len(array)
output := make([]int, n)
count := make([]int, 10)

for i := 0; i < n; i++ {
index := (array[i] / exp) % 10
count[index]++
}

for i := 1; i < 10; i++ {
count[i] += count[i-1]
}

for i := n - 1; i >= 0; i-- {
index := (array[i] / exp) % 10
output[count[index]-1] = array[i]
count[index]--
}

for i := 0; i < n; i++ {
array[i] = output[i]
}
}

max := getMax(arr)

exp := 1
for exp <= max {
countingSort(arr, exp)
exp *= 10
}
}

func main() {
array := []int{15, 65, 32, 34, 435, 87, 56, 86}
fmt.Println("Array after sorting :", array)
}


## Output

Array after sorting: [15 32 34  56 65 86 87 435]


## Conclusion

In this article we have checked how we can perform the radix sort on an unsorted array and then print a sorted array using different methods using golanguage. We explored the implementation of this program using repetition, Iteration as well as in-place radi sort.

Updated on: 06-Jul-2023

60 Views 