Sorting algorithms/Counting sort: Difference between revisions

→‎{{header|Julia}}: A new entry for Julia
(→‎{{header|Julia}}: A new entry for Julia)
Line 967:
$ jq -M -c -n -f counting_sort.jq
[0,1,1,2,4,10]</lang>
 
=={{header|Julia}}==
This is a translation of the pseudocode presented in the task description, accounting for the fact that Julia arrays start indexing at 1 rather than zero and taking care to return a result of the same type as the input. Note that <code>cnt</code> has the machine's standard integer type (typically <code>Int64</code>), which need not match that of the input.
 
<lang Julia>
function countsort{T<:Integer}(a::Array{T,1})
(lo, hi) = extrema(a)
b = zeros(T, length(a))
cnt = zeros(Int, hi - lo + 1)
for i in a
cnt[i - lo + 1] += 1
end
z = one(Int)
for i in lo:hi
while cnt[i - lo + 1] > 0
b[z] = i
z += 1
cnt[i - lo + 1] -= 1
end
end
return b
end
 
a = Uint8[rand(1:typemax(Uint8)) for i in 1:20]
println("Sort of Unsigned Bytes:")
println(" Before Sort:")
println(" ", a)
a = countsort(a)
println("\n After Sort:")
println(" ", a, "\n")
 
a = [rand(1:2^10) for i in 1:20]
println("Sort of Integers:")
println(" Before Sort:")
println(" ", a)
a = countsort(a)
println("\n After Sort:")
println(" ", a)
<lang>
 
{{out}}
<pre>
Sort of Unsigned Bytes:
Before Sort:
Uint8[141,195,133,61,53,93,76,86,112,83,106,56,50,104,162,183,33,180,59,91]
 
After Sort:
Uint8[33,50,53,56,59,61,76,83,86,91,93,104,106,112,133,141,162,180,183,195]
 
Sort of Integers:
Before Sort:
[961,781,70,916,1013,208,80,402,148,459,264,384,5,713,100,725,397,701,218,211]
 
After Sort:
[5,70,80,100,148,208,211,218,264,384,397,402,459,701,713,725,781,916,961,1013]
</pre>
 
=={{header|Lua}}==