Implementation of Counting Sort

Implement counting sort using prefix sums in Go. Discover non-comparison sorting with efficient O(n) time complexity execution.

Read in: ja
Implementation of Counting Sort

What is Counting Sort

Counting Sort is an unusual sorting algorithm that sorts without using comparisons.

It can sort by counting elements instead of comparing them.

I found it fascinating that sorting can be done by counting, so I decided to look into it.

Prerequisites

You need to know about prefix sums.

cf. qiita.com - What is a Prefix Sum (For Beginners)

Implementation

The source code is as follows.

count_sort

package main

import "fmt"

func countSort(s []int, maxVal int) []int {
	count := make([]int, maxVal+1)

	// Count
	for _, num := range s {
		count[num]++
	}

	// Calculate prefix sums
	// ex. [1, 2, 3, 4, 5] → [1, 3, 6, 10, 15]
	for i := 1; i <= maxVal; i++ {
		count[i] += count[i-1]
	}

	sorted := make([]int, len(s))

	// Traverse the original array from the end and place elements in the sorted result
	for i := len(s) - 1; i >= 0; i-- {
		num := s[i]
		count[num]--
		sorted[count[num]] = num
	}

	return sorted
}

func main() {
	s := []int{5, 3, 2, 1, 2, 3, 4}
	maxVal := 5
	r := countSort(s, maxVal)
	fmt.Println(r)
}
// Output
[1 2 2 3 3 4 5]

The process flow is as follows:

  1. Count the occurrences of each element in the array using the elements as indices
  2. Calculate the prefix sums
  3. Traverse the array from the end to get the sorted result

It feels very mathematical rather than intuitive.

References

Tags: Counting Sort
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles