Sorting algorithms/Counting sort: Difference between revisions
Content deleted Content added
m →version 1: removed the need for the I DO loop, the finding of the MIN and MAX was incorporated into the J DO loop. |
Added Elixir |
||
Line 561: | Line 561: | ||
sorted: |
sorted: |
||
-7 1 2 3 4 6 |
-7 1 2 3 4 6 |
||
</pre> |
|||
=={{header|Elixir}}== |
|||
<lang elixir>defmodule Sort do |
|||
def counting_sort([]), do: [] |
|||
def counting_sort(list) do |
|||
{min, max} = minmax(list) |
|||
count = List.to_tuple(for _ <- min..max, do: 0) |
|||
counted = Enum.reduce(list, count, fn x,acc -> |
|||
i = x - min |
|||
put_elem(acc, i, elem(acc, i) + 1) |
|||
end) |
|||
Enum.reduce(max..min, [], fn n,acc -> |
|||
m = elem(counted, n - min) |
|||
List.duplicate(n, m) ++ acc |
|||
end) |
|||
end |
|||
defp minmax([h|t]), do: minmax(t, h, h) |
|||
defp minmax([], min, max), do: {min, max} |
|||
defp minmax([h|t], min, max) when h<min, do: minmax(t, h, max) |
|||
defp minmax([h|t], min, max) when max<h, do: minmax(t, min, h) |
|||
defp minmax([_|t], min, max) , do: minmax(t, min, max) |
|||
end |
|||
IO.inspect Sort.counting_sort([1,-2,-3,2,1,-5,5,5,4,5,9])</lang> |
|||
{{out}} |
|||
<pre> |
|||
[-5, -3, -2, 1, 1, 2, 4, 5, 5, 5, 9] |
|||
</pre> |
</pre> |
||