Skip to content

Commit b69de8c

Browse files
Adding counting sort
1 parent 104149b commit b69de8c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Go/sorting/countingsort.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package sorting
2+
3+
// Note: The array can be sorted by using this algorithm only if the maximum value in array is less than the
4+
// maximum size of the array . Usually, it is possible to allocate memory up to the order of a million .
5+
// If the maximum value of exceeds the maximum memory- allocation size, it is recommended that you do not use this algorithm.
6+
// Use either the quick sort or merge sort algorithm.
7+
func countingSort(arr []int) {
8+
max := len(arr)
9+
10+
for i := 0; i < len(arr); i++ {
11+
if arr[i] > max {
12+
max = arr[i]
13+
}
14+
}
15+
16+
aux := make([]int, max+1)
17+
18+
for i := 0; i < len(arr); i++ {
19+
aux[arr[i]]++
20+
}
21+
22+
k := 0
23+
for i := 0; i < len(aux); i++ {
24+
for aux[i] != 0 {
25+
arr[k] = i
26+
aux[i]--
27+
k++
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)