Jump to content

Sorting algorithms/Counting sort: Difference between revisions

(Cleaned D code)
(→‎{{header|Groovy}}: new solution)
Line 399:
}
}</lang>
 
=={{header|Groovy}}==
Solution:
<lang groovy>def countingSort = { array ->
def max = array.max()
def min = array.min()
// this list size allows use of Groovy's natural negative indexing
def count = [0] * (max + 1 + [0, -min].max())
array.each { count[it] ++ }
(min..max).findAll{ count[it] }.collect{ [it]*count[it] }.flatten()
}</lang>
 
Test:
<lang groovy>println countingSort([15,-3,0,-1,5,4,5,20,-8])
println countingSort([34,6,8,7,4,3,56,7,8,4,3,5,7,8,6,4,4,67,9,0,0,76,467,453,34,435,37,4,34,234,435,3,2,7,4,634,534,-735,5,4,6,78,4])
// slo-o-o-o-ow due to unnecessarily large counting array
println countingSort([10000033,10000006,10000008,10000009,10000013,10000031,10000013,10000032,10000023,10000023,10000011,10000012,10000021])</lang>
 
Output:
<pre>[-8, -3, -1, 0, 4, 5, 5, 15, 20]
[-735, 0, 0, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 34, 34, 34, 37, 56, 67, 76, 78, 234, 435, 435, 453, 467, 534, 634]
[10000006, 10000008, 10000009, 10000011, 10000012, 10000013, 10000013, 10000021, 10000023, 10000023, 10000031, 10000032, 10000033]</pre>
 
=={{header|Haskell}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.