Sorting algorithms/Counting sort: Difference between revisions

Content deleted Content added
Rdm (talk | contribs)
J: clarify and illustrate an alternative
Line 589: Line 589:
Alternative implementation:
Alternative implementation:


<lang J>csort=: (+/@(=/) # ]) >./ (] + 1 i.@+ -) <./</lang>
<lang j>csort=: (+/@(=/) # ]) >./ (] + 1 i.@+ -) <./</lang>


And note that this can be simplified if the range is known in advance (which would probably be the case -- this sorting mechanism is practical when we have a small fixed range of values that we are sorting.


'''Example:'''
'''Example:'''
Line 598: Line 597:


csort a
csort a
_3 _2 _2 _1 _1 _1 0 1 1 3 3 4 4 4 4 4 5 5 6 6</lang>

And note that this can be further simplified if the range is known in advance (which could easily be the case -- this sorting mechanism is practical when we have a small fixed range of values that we are sorting). Here, we do not need to inspect the data to find min and max values, since they are already known:

<lang j>csrt=:2 :0
(m+i.n-m) (+/@(=/)~ # [) ]
)</lang>

Example:

<lang j> (_3 csrt 17) a
_3 _2 _2 _1 _1 _1 0 1 1 3 3 4 4 4 4 4 5 5 6 6</lang>
_3 _2 _2 _1 _1 _1 0 1 1 3 3 4 4 4 4 4 5 5 6 6</lang>