Sorting algorithms/Radix sort: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Merge introductory paragraphs)
m (whitespace)
Line 7: Line 7:
<code>keys f/. data </code> evaluates the function f on each group of data at the same position as similar keys. Sorting requires ordered keys. This code uses a J idiom: prepend the keys and matching data. The extra data is removed by behead <code>}.</code>.
<code>keys f/. data </code> evaluates the function f on each group of data at the same position as similar keys. Sorting requires ordered keys. This code uses a J idiom: prepend the keys and matching data. The extra data is removed by behead <code>}.</code>.


<lang j>NB. queue implementation of LSB radix sort.
<lang j>
NB. queue implementation of LSB radix sort.
radixSort =: 3 : 0 NB. base radixSort data
radixSort =: 3 : 0 NB. base radixSort data
16 radixSort y
16 radixSort y
Line 20: Line 19:
end.
end.
x#.keys NB. restore the data
x#.keys NB. restore the data
)</lang>
)
</lang>


Sort 10 small numbers in base 3.
Sort 10 small numbers in base 3.

Revision as of 10:42, 19 January 2011

Task
Sorting algorithms/Radix sort
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to sort an integer array with the radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.

J

Generally, this task should be accomplished in J using /:~. Here we take an approach that's more comparable with the other examples on this page.

keys f/. data evaluates the function f on each group of data at the same position as similar keys. Sorting requires ordered keys. This code uses a J idiom: prepend the keys and matching data. The extra data is removed by behead }..

<lang j>NB. queue implementation of LSB radix sort. radixSort =: 3 : 0 NB. base radixSort data 16 radixSort y

keys =. x #.^:_1 y NB. compute keys length =. {:#{.keys extra =. (x,-length) {. ,. buckets =. i.x for_pass. 0{i.-length do.

 keys =. ,&:>/ (buckets,keys{~"1<pass) <@:}./.extra,keys
 extra =. 1 |. extra

end. x#.keys NB. restore the data )</lang>

Sort 10 small numbers in base 3.

   (,: 3&radixSort) ?@#~10
1 3 8 9 0 0 8 7 1 6
0 0 1 1 3 6 7 8 8 9

Python

The wikipedia article cited in the introduction includes a python implementation of LSB radix sort.