package main import ( "fmt" ) func bubbleSort(arr []int) { for i := 0; i < len(arr)-1; i++ { for j := 0; j < len(arr)-i-1; j++ { if arr[j] > arr[j+1] { arr[j], arr[j+1] = arr[j+1], arr[j] } } } } func main() { arr := []int{5, 3, 8, 4, 2} bubbleSort(arr) fmt.Println(arr) }
The bubble sort algorithm compares adjacent elements and swaps them if the left element is greater than the right. After all passes, the array is sorted in ascending order.
package main import ( "fmt" ) func countingSort(arr []int) []int { max := arr[0] for _, v := range arr { if v > max { max = v } } count := make([]int, max+1) for _, v := range arr { count[v]++ } index := 0 for i, c := range count { for c > 0 { arr[index] = i index++ c-- } } return arr } func main() { arr := []int{4, 2, 2, 8, 3, 3, 1} sortedArr := countingSort(arr) fmt.Println(sortedArr) }
Counting sort counts how many times each number appears and then writes them back in order. This produces a sorted array in ascending order.
Comparison based sorting algorithms cannot be faster than O(n log n) in the worst case. Non comparison based algorithms like counting sort can run in O(n) if input constraints allow.
package main import ( "fmt" ) func countingSortForRadix(arr []int, exp int) []int { output := make([]int, len(arr)) count := make([]int, 10) for i := 0; i < len(arr); i++ { index := (arr[i] / exp) % 10 count[index]++ } for i := 1; i < 10; i++ { count[i] += count[i-1] } for i := len(arr) - 1; i >= 0; i-- { index := (arr[i] / exp) % 10 output[count[index]-1] = arr[i] count[index]-- } return output } func radixSort(arr []int) []int { max := arr[0] for _, v := range arr { if v > max { max = v } } exp := 1 for max/exp > 0 { arr = countingSortForRadix(arr, exp) exp *= 10 } return arr } func main() { arr := []int{170, 45, 75, 90, 802, 24, 2, 66} sortedArr := radixSort(arr) fmt.Println(sortedArr) }
The count array stores cumulative counts, so the correct index to place the element is count[index] - 1, not count[index]. Using count[index] causes an off-by-one error and overwrites data.
Counting Sort is ideal here because the input range (0 to 1000) is small compared to the number of elements (10 million). It sorts in O(n + k) time, which is efficient for this case.