forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounting_Sort.coffee
More file actions
38 lines (25 loc) · 750 Bytes
/
Counting_Sort.coffee
File metadata and controls
38 lines (25 loc) · 750 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
counting_sort = (input) ->
output = Array(input.length).fill(0)
max = output[0]
min = output[0]
for i in [0...input.length]
if input[i] > max
max = input[i]
else if input[i] < min
min = input[i]
k = max - min + 1
count_array = Array(k).fill(0)
for i in [0...input.length]
count_array[input[i] - min] += 1
for i in [1...k]
count_array[i] += count_array[i - 1]
for i in [0...input.length]
output[count_array[input[i] - min] - 1] = input[i]
count_array[input[i] - min] -= 1
output
input = [1, 5, 2, 7, 3, 4, 4, 1, 5]
input = counting_sort input
console.log "Sorted array : " + input
### Output
Sorted array : 1,1,2,3,4,4,5,5,7
###