Sorting algorithms/Radix sort: Difference between revisions

Added uBasic/4tH version
m (→‎{{header|Tailspin}}: syntax update)
imported>Thebeez
(Added uBasic/4tH version)
 
(48 intermediate revisions by 18 users not shown)
Line 1:
{{task|Sorting Algorithms}}
[[Category:Sorting]]
{{Sorting Algorithm}}
 
Line 8 ⟶ 9:
The primary purpose is to complete the characterization of sort algorithms task.
<br><br>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F flatten(some_list)
[Int] new_list
L(sub_list) some_list
new_list [+]= sub_list
R new_list
 
F radix_sort(l, =p = -1, =s = -1)
I s == -1
s = String(max(l)).len
I p == -1
p = s
 
V i = s - p
I i >= s
R l
 
V bins = [[Int]()] * 10
 
L(e) l
bins[Int(String(e).zfill(s)[i])] [+]= e
 
R flatten(bins.map(b -> radix_sort(b, @p - 1, @s)))
 
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
print(radix_sort(arr))</syntaxhighlight>
 
{{out}}
<pre>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program radixSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .quad 12485,301,16,25,5006,9,-154389710,26,4400,71,115
#TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0 // first element
mov x2,NBELEMENTS // number of élements
bl radixSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
beq 1f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
1: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* radix sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
/* no registers save */
radixSort:
str lr,[sp,-16]! // save 1 register
mov x7,0b1111 // mask one digit hexa
mov x10,0 // digit counter
1:
add x3,x1,1 // start index i
2: // start loop
ldr x4,[x0,x3,lsl 3] // load value A[i]
and x8,x4,x7 // and mask
sub x5,x3,1 // index j
3:
ldr x6,[x0,x5,lsl 3] // load value A[j]
and x9,x6,x7 // and mask
cmp x9,x8 // compare one digit hexa
ble 4f
add x5,x5,1 // increment index j
str x6,[x0,x5,lsl 3] // store value A[j+1]
sub x5,x5,2 // j = j - 1
cmp x5,x1
bge 3b // loop if j >= first item
4:
add x5,x5,1 // increment index j
str x4,[x0,x5,lsl 3] // store value A[i] in A[j+1]
add x3,x3,1 // increment index i
cmp x3,x2 // end ?
blt 2b // no -> loop
//bl displayTable
lsl x7,x7,4 // shift mask 4 bits left
add x10,x10,1 // increment counter
cmp x10,16 // 16 digits ?
blt 1b // no loop
100:
 
ldr lr,[sp],16 // restaur 1 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at // character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Value : -154389710
Value : +9
Value : +16
Value : +25
Value : +26
Value : +71
Value : +115
Value : +301
Value : +4400
Value : +5006
Value : +12485
 
Table sorted.
</pre>
 
=={{header|Ada}}==
 
radix_sort.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Radix_Sort is
type Integer_Array is array (Positive range <>) of Integer;
Line 94 ⟶ 316:
end loop;
Ada.Text_IO.New_Line;
end Radix_Sort;</langsyntaxhighlight>
 
output:
<pre>-802-90 2 24 45 66 75 170</pre>
 
 
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">PROC radixsort = (REF []INT array) VOID:
(
[UPB array]INT zero;
Line 151 ⟶ 371:
radixsort(a);
print(("After: ", a))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 158 ⟶ 378:
After: +129 +160 +263 +328 +386 +459 +554 +623 +766 +941
</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program radixSort1.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .int 1,110,30,6,201,5004,29,10,1008,4,7,-25000
#TableNumber: .int 10,9,8,7,6,5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrTableNumber @ address number table
mov r1,#0 @ first element
mov r2,#NBELEMENTS @ number of élements
bl radixSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 1f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
1: @ yes
ldr r0,iAdrszMessSortOk
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements > 0 */
/* r0 return 0 if not sorted 1 if sorted */
isSorted:
push {r2-r4,lr} @ save registers
mov r2,#0
ldr r4,[r0,r2,lsl #2]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/******************************************************************/
/* radix sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
radixSort:
push {r3-r10,lr} @ save registers
mov r7,#0b1111 @ mask one digit hexa
mov r10,#0 @ digit counter
1:
add r3,r1,#1 @ start index i
2: @ start loop
ldr r4,[r0,r3,lsl #2] @ load value A[i]
and r8,r4,r7 @ and mask
sub r5,r3,#1 @ index j
3:
ldr r6,[r0,r5,lsl #2] @ load value A[j]
and r9,r6,r7 @ and mask
cmp r9,r8 @ compare one digit hexa
ble 4f
add r5,#1 @ increment index j
str r6,[r0,r5,lsl #2] @ store value A[j+1]
sub r5,#2 @ j = j - 1
cmp r5,r1
bge 3b @ loop if j >= first item
4:
add r5,#1 @ increment index j
str r4,[r0,r5,lsl #2] @ store value A[i] in A[j+1]
add r3,#1 @ increment index i
cmp r3,r2 @ end ?
blt 2b @ no -> loop
//bl displayTable
lsl r7,#4 @ shift mask 4 bits left
add r10,r10,#1 @ increment counter
cmp r10,#8 @ 8 digits ?
blt 1b @ no loop
100:
pop {r3-r10,lr}
bx lr @ return
 
 
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsZoneConv @
bl conversion10S @ décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
mov r0,r2
100:
pop {r0-r3,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
Value : -25000
Value : +1
Value : +4
Value : +6
Value : +7
Value : +10
Value : +29
Value : +30
Value : +110
Value : +201
Value : +1008
Value : +5004
 
Table sorted.
</pre>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">radixSort: function [items][
base: 10
a: new items
rounds: inc floor (ln max a)/ln base
loop rounds 'i [
buckets: array.of: 2*base []
baseI: base ^ i
loop a 'n [
digit: last digits n
if n >= 0 -> digit: digit + base
buckets\[digit]: buckets\[digit] ++ n
]
a: new flatten buckets
]
return a
]
 
print radixSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|ATS}}==
 
<syntaxhighlight lang="ats">(*
Stable integer-keyed radix sorts for unsigned and signed integers
of the various typekinds.
 
The radix is 256.
*)
 
(*------------------------------------------------------------------*)
 
#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"
 
(*------------------------------------------------------------------*)
 
extern fn {a : vt@ype}
{tk : tkind}
g0uint_radix_sort
{n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void
 
extern fn {a : vt@ype}
{tk : tkind}
g0uint_radix_sort$key
{n : int}
{i : nat | i < n}
(arr : &RD(array (a, n)),
i : size_t i)
:<> g0uint tk
 
(*------------------------------------------------------------------*)
 
extern fn {a : vt@ype}
{tki, tku : tkind}
g0int_radix_sort
{n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void
 
extern fn {a : vt@ype}
{tki : tkind}
g0int_radix_sort$key
{n : int}
{i : nat | i < n}
(arr : &RD(array (a, n)),
i : size_t i)
:<> g0int tki
 
(*------------------------------------------------------------------*)
 
(* WARNING: Much of the following code does NOT take into account
the linearity of array entries. But this unsafeness is
hidden from the user. *)
 
fn {}
bin_sizes_to_indices
(bin_indices : &array (size_t, 256) >> _)
:<!wrt> void =
let
fun
loop {i : int | i <= 256}
{accum : int}
.<256 - i>.
(bin_indices : &array (size_t, 256) >> _,
i : size_t i,
accum : size_t accum)
:<!wrt> void =
if i <> i2sz 256 then
let
prval () = lemma_g1uint_param i
val elem = bin_indices[i]
in
if elem = i2sz 0 then
loop (bin_indices, succ i, accum)
else
begin
bin_indices[i] := accum;
loop (bin_indices, succ i, accum + g1ofg0 elem)
end
end
in
loop (bin_indices, i2sz 0, i2sz 0)
end
 
fn {a : vt@ype}
{tk : tkind}
count_entries
{n : int}
{shift : nat}
(arr : &RD(array (a, n)),
n : size_t n,
bin_indices : &array (size_t?, 256)
>> array (size_t, 256),
all_expended : &bool? >> bool,
shift : int shift)
:<!wrt> void =
let
fun
loop {i : int | i <= n}
.<n - i>.
(arr : &RD(array (a, n)),
bin_indices : &array (size_t, 256) >> _,
all_expended : &bool >> bool,
i : size_t i)
:<!wrt> void =
if i <> n then
let
prval () = lemma_g1uint_param i
val key : g0uint tk = g0uint_radix_sort$key<a><tk> (arr, i)
val key_shifted = key >> shift
val digit = ($UN.cast{uint} key_shifted) land 255U
val [digit : int] digit = g1ofg0 digit
extern praxi set_range :
() -<prf> [0 <= digit; digit <= 255] void
prval () = set_range ()
val count = bin_indices[digit]
val () = bin_indices[digit] := succ count
in
all_expended := all_expended * iseqz key_shifted;
loop (arr, bin_indices, all_expended, succ i)
end
 
prval () = lemma_array_param arr
in
array_initize_elt<size_t> (bin_indices, i2sz 256, i2sz 0);
all_expended := true;
loop (arr, bin_indices, all_expended, i2sz 0)
end
 
fn {a : vt@ype}
{tk : tkind}
sort_by_digit
{n : int}
{shift : nat}
(arr1 : &RD(array (a, n)),
arr2 : &array (a, n) >> _,
n : size_t n,
all_expended : &bool? >> bool,
shift : int shift)
:<!wrt> void =
let
var bin_indices : array (size_t, 256)
in
count_entries<a><tk> (arr1, n, bin_indices, all_expended, shift);
if all_expended then
()
else
let
fun
rearrange {i : int | i <= n}
.<n - i>.
(arr1 : &RD(array (a, n)),
arr2 : &array (a, n) >> _,
bin_indices : &array (size_t, 256) >> _,
i : size_t i)
:<!wrt> void =
if i <> n then
let
prval () = lemma_g1uint_param i
val key = g0uint_radix_sort$key<a><tk> (arr1, i)
val key_shifted = key >> shift
val digit = ($UN.cast{uint} key_shifted) land 255U
val [digit : int] digit = g1ofg0 digit
extern praxi set_range :
() -<prf> [0 <= digit; digit <= 255] void
prval () = set_range ()
val [j : int] j = g1ofg0 bin_indices[digit]
 
(* One might wish to get rid of this assertion somehow,
to eliminate the branch, should it prove a
problem. *)
val () = $effmask_exn assertloc (j < n)
 
val p_dst = ptr_add<a> (addr@ arr2, j)
and p_src = ptr_add<a> (addr@ arr1, i)
val _ = $extfcall (ptr, "memcpy", p_dst, p_src,
sizeof<a>)
val () = bin_indices[digit] := succ (g0ofg1 j)
in
rearrange (arr1, arr2, bin_indices, succ i)
end
 
prval () = lemma_array_param arr1
in
bin_sizes_to_indices<> bin_indices;
rearrange (arr1, arr2, bin_indices, i2sz 0)
end
end
 
fn {a : vt@ype}
{tk : tkind}
g0uint_sort {n : pos}
(arr1 : &array (a, n) >> _,
arr2 : &array (a, n) >> _,
n : size_t n)
:<!wrt> void =
let
fun
loop {idigit_max, idigit : nat | idigit <= idigit_max}
.<idigit_max - idigit>.
(arr1 : &array (a, n) >> _,
arr2 : &array (a, n) >> _,
from1to2 : bool,
idigit_max : int idigit_max,
idigit : int idigit)
:<!wrt> void =
if idigit = idigit_max then
begin
if ~from1to2 then
let
val _ =
$extfcall (ptr, "memcpy", addr@ arr1, addr@ arr2,
sizeof<a> * n)
in
end
end
else if from1to2 then
let
var all_expended : bool
in
sort_by_digit<a><tk> (arr1, arr2, n, all_expended,
8 * idigit);
if all_expended then
()
else
loop (arr1, arr2, false, idigit_max, succ idigit)
end
else
let
var all_expended : bool
in
sort_by_digit<a><tk> (arr2, arr1, n, all_expended,
8 * idigit);
if all_expended then
let
val _ =
$extfcall (ptr, "memcpy", addr@ arr1, addr@ arr2,
sizeof<a> * n)
in
end
else
loop (arr1, arr2, true, idigit_max, succ idigit)
end
in
loop (arr1, arr2, true, sz2i sizeof<g1uint tk>, 0)
end
 
#define SIZE_THRESHOLD 256
 
extern praxi
unsafe_cast_array
{a : vt@ype}
{b : vt@ype}
{n : int}
(arr : &array (b, n) >> array (a, n))
:<prf> void
 
implement {a} {tk}
g0uint_radix_sort {n} (arr, n) =
if n <> 0 then
let
prval () = lemma_array_param arr
 
fn
sort {n : pos}
(arr1 : &array (a, n) >> _,
arr2 : &array (a, n) >> _,
n : size_t n)
:<!wrt> void =
g0uint_sort<a><tk> (arr1, arr2, n)
in
if n <= SIZE_THRESHOLD then
let
var arr2 : array (a, SIZE_THRESHOLD)
prval @(pf_left, pf_right) =
array_v_split {a?} {..} {SIZE_THRESHOLD} {n} (view@ arr2)
prval () = view@ arr2 := pf_left
prval () = unsafe_cast_array{a} arr2
 
val () = sort (arr, arr2, n)
 
prval () = unsafe_cast_array{a?} arr2
prval () = view@ arr2 :=
array_v_unsplit (view@ arr2, pf_right)
in
end
else
let
val @(pf_arr2, pfgc_arr2 | p_arr2) = array_ptr_alloc<a> n
macdef arr2 = !p_arr2
prval () = unsafe_cast_array{a} arr2
 
val () = sort (arr, arr2, n)
 
prval () = unsafe_cast_array{a?} arr2
val () = array_ptr_free (pf_arr2, pfgc_arr2 | p_arr2)
in
end
end
 
(*------------------------------------------------------------------*)
 
fn {a : vt@ype}
{tki, tku : tkind}
g0int_sort {n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void =
let
macdef get_key = g0int_radix_sort$key<a><tki>
prval () = lemma_array_param arr
in
if n = 0 then
()
else
let
val () = $effmask_exn
assertloc (sizeof<g0int tki> = sizeof<g0uint tku>)
 
fn
find_least_key (arr : &RD(array (a, n)))
:<> g0int tki =
let
fun
loop {i : int | i <= n}
.<n - i>.
(arr : &RD(array (a, n)),
least_key : g0int tki,
i : size_t i)
:<> g0int tki =
if i <> n then
let
prval () = lemma_g1uint_param i
val key = get_key (arr, i)
in
loop (arr, min (least_key, key), succ i)
end
else
least_key
in
if n = 0 then
get_key (arr, i2sz 0)
else
let
val first_key = get_key (arr, i2sz 0)
in
loop (arr, first_key, i2sz 1)
end
end
 
val least_key = find_least_key arr
 
(* The offset is the two's complement of the least key. Thus the
least key is mapped to zero and the order of keys is
preserved. *)
val offset = succ (lnot ($UN.cast{g1uint tku} least_key))
 
implement
g0uint_radix_sort$key<a><tku> (arr, i) =
let
val keyi = get_key (arr, i)
in
g0i2u keyi + offset
end
in
g0uint_radix_sort<a><tku> (arr, n)
end
end
 
implement {a} {tki, tku}
g0int_radix_sort (arr, n) =
g0int_sort<a><tki, tku> (arr, n)
 
(*------------------------------------------------------------------*)
 
implement
main0 () =
let
implement
g0int_radix_sort$key<int><intknd> (arr, i) =
arr[i]
 
var arr : array (int, 10)
val () =
array_initize_list<int>
(arr, 10, $list (1, 2, 1, ~2, 330, 5000, 16, ~20000, 1, 2))
val () = g0int_radix_sort<int><intknd, uintknd> (arr, i2sz 10)
val () = println! (list_vt2t (array2list (arr, i2sz 10)))
in
end
 
(*------------------------------------------------------------------*)</syntaxhighlight>
 
{{out}}
<pre>$ patscc -O3 -DATS_MEMALLOC_LIBC radix_sort_task.dats && ./a.out
-20000, -2, 1, 1, 1, 2, 2, 16, 330, 5000</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Radix_Sort(data){
loop, parse, data, `,
n := StrLen(A_LoopField)>n?StrLen(A_LoopField):n
Line 172 ⟶ 1,001:
}
return data
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">d = 170,45,75,90,802,2,24,66
MsgBox, 262144, , % Radix_Sort(d)</langsyntaxhighlight>
Outputs:<pre>2,24,45,66,75,90,170,802</pre>
 
=={{header|B4X}}==
<syntaxhighlight lang="b4x">Sub RadixSort (Old() As Int)
Dim i, j As Int
Dim tmp(Old.Length) As Int
For shift = 31 To 0 Step - 1
j = 0
For i = 0 To Old.Length - 1
Dim move As Boolean = Bit.ShiftLeft(Old(i), shift) >= 0
If (shift = 0 And move = False) Or (shift <> 0 And move) Then
Old(i - j) = Old(i)
Else
tmp(j) = Old(i)
j = j + 1
End If
Next
Bit.ArrayCopy(tmp, 0, Old, Old.Length - j, j)
Next
End Sub
 
Sub Test
Dim arr() As Int = Array As Int(34, 23, 54, -123, 543, 123)
RadixSort(arr)
For Each i As Int In arr
Log(i)
Next
End Sub</syntaxhighlight>
'''Output:'''
<pre>
-123
23
34
54
123
543
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
The array index is assumed to start at zero. The third parameter of PROCradixsort() is the radix used.
<langsyntaxhighlight lang="bbcbasic"> DIM test%(9)
test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCradixsort(test%(), 10, 10)
Line 216 ⟶ 1,081:
ENDWHILE
a%() += l%
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 223 ⟶ 1,088:
 
=={{header|C}}==
Radix sort, "digits" are most significant bits.<langsyntaxhighlight lang="c">#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
Line 288 ⟶ 1,153:
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}</langsyntaxhighlight>output<pre>-182 -175 -151 -141 -70 -51 -20 -5 -1 41 70 103 171 198 227 242</pre>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
<syntaxhighlight lang="csharp">using System;
 
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move) // shift the 0's to old's head
old[i-j] = old[i];
else // move the 1's to tmp
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
Line 294 ⟶ 1,196:
 
Note: the LSD radix sort uses the standard library '''std::stable_partition''' algorithm. This algorithm is guaranteed to preserve relative order and has a higher runtime cost. The MSD radix sort uses '''std::partition''' and can be significantly faster.
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iterator>
Line 346 ⟶ 1,248:
 
return 0;
}</langsyntaxhighlight>
Output:
<pre>-802 -90 2 24 45 66 75 170 </pre>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
<lang csharp>using System;
 
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move) // shift the 0's to old's head
old[i-j] = old[i];
else // move the 1's to tmp
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}</lang>
 
=={{header|D}}==
===Shorter Version===
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.traits, std.range, std.algorithm;
 
ElementType!R[] radixSort(size_t N=10, R)(R r)
Line 421 ⟶ 1,286:
items.radixSort().writeln();
items.map!q{1 - a}().radixSort().writeln();
}</langsyntaxhighlight>
{{out}}
<pre>[-802, -90, 2, 24, 45, 66, 75, 170]
Line 427 ⟶ 1,292:
 
===More Efficient Version===
<langsyntaxhighlight lang="d">import std.array, std.traits;
 
// considered pure for this program
Line 484 ⟶ 1,349:
items.radixSort();
writeln(items);
}</langsyntaxhighlight>
{{out}}
<pre>[2, 24, 45, 66, 75, 170, 4294966494, 4294967206]</pre>
Line 492 ⟶ 1,357:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang># only works with positive integers
proc sort . d[] .
#
# radix = 10
subr sort
radix = 16256
max = 0
for di range= 1 to len datad[]
if datad[di] > max
max = datad[di]
.
.
len buck[][] radix
pos = 1
while pos <= max
for i range radix
len buck[i][] 0
.
for di range len data[]
h = data[di] / pos mod radix
buck[h][] &= data[di]
.
di = 0
for i range radix
for j range len buck[i][]
data[di] = buck[i][j]
di += 1
.
.
len pos *=buck[][] radix
pos = 1
.
while pos <= max
for i = 1 to radix
len buck[i][] 0
.
for di = 1 to len d[]
h = d[di] div pos mod radix + 1
buck[h][] &= d[di]
.
di = 1
for i = 1 to radix
for j = 1 to len buck[i][]
d[di] = buck[i][j]
di += 1
.
.
pos *= radix
.
.
data[] = [ 29 4 72 44 55 26 27 77 92 5 ]
call sort data[]
print data[]</lang>
</syntaxhighlight>
 
=={{header|Eiffel}}==
Works for positive integers. Splits up into two buckets according to the binary representation of the number.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
RADIX_SORT
Line 621 ⟶ 1,487:
 
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 657 ⟶ 1,523:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 668 ⟶ 1,534:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Sort do
def radix_sort(list), do: radix_sort(list, 10)
Line 691 ⟶ 1,557:
end
 
IO.inspect Sort.radix_sort([-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028])</langsyntaxhighlight>
 
{{out}}
Line 699 ⟶ 1,565:
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
 
SUBROUTINE VARRADIX(A , Siz)
 
!
! No Copyright is exerted due to considerable prior art in the Public Domain.
! This Fortran version by Peter Kelly ~ peter.kelly@acm.org
!
! Permission is hereby granted, free of charge, to any person obtaining
! a copy of this software and associated documentation files (the
! "Software"), to deal in the Software without restriction, including
! without limitation the rights to use, copy, modify, merge, publish,
! distribute, sublicense, and/or sell copies of the Software, and to
! permit persons to whom the Software is furnished to do so, subject to
! the following conditions:
! The above copyright notice and this permission notice shall be
! included in all copies or substantial portions of the Software.
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
! EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
! MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
! IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
! CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
! TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
! SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!
!
! LSD sort with a configurable RADIX, Using a RADIX of 256 performs well, hence I have defaulted it in. It is snarly fast.
! It could be optimized by merging the two routines but this way gives greater clarity as to what's going on.
IMPLICIT NONE
!
! PARAMETER definitions
!
INTEGER , PARAMETER :: BASE = 256 ! whatever base you need, just change this
!
! Dummy arguments
!
INTEGER :: Siz
INTEGER , DIMENSION(Siz) :: A
!
! Local variables
!
INTEGER , ALLOCATABLE , DIMENSION(:) :: b
INTEGER , ALLOCATABLE , DIMENSION(:) :: c
INTEGER :: exps
INTEGER :: maxs
!
ALLOCATE(b(Siz))
ALLOCATE(c(BASE))
exps = 1
maxs = MAXVAL(A)
DO WHILE ( (maxs/exps)>0 )
CALL XXCOUNTING_SORT(A , Siz , exps , BASE , b , c)
exps = exps*BASE
END DO
deallocate(C)
deallocate(B)
RETURN
CONTAINS
!
!//b is the base you want
!//exp is the value used for the division
SUBROUTINE XXCOUNTING_SORT(A , Siz , Exps , Base , B , C)
IMPLICIT NONE
! I used zero based arrays as it made the calcs infinitely easier :)
!
! Dummy arguments
!
INTEGER :: Base
INTEGER :: Exps
INTEGER :: Siz ! Size
INTEGER , DIMENSION(0:) :: A
INTEGER , DIMENSION(0:) :: B
INTEGER , DIMENSION(0:) :: C
INTENT (IN) Base , Exps , Siz
INTENT (INOUT) A , B , C
!
! Local variables
!
INTEGER :: i
INTEGER :: k
!
C = 0 ! Init the arrays
B = 0
!
DO i = 0 , Siz - 1 , 1
k = MOD((A(i)/Exps) , Base) ! Fill Histo
C(k) = C(k) + 1
END DO
!
DO i = 1 , Base - 1 , 1
C(i) = C(i) + C(i - 1) ! Build cumulative Histo
END DO
!
DO i = Siz - 1 , 0 , -1
k = MOD(A(i)/Exps , Base) ! Load the Buffer Array in order
B(C(k) - 1) = A(i)
C(k) = C(k) - 1
END DO
!
DO i = 0 , Siz - 1 , 1 ! Copy across
A(i) = B(i)
END DO
RETURN
END SUBROUTINE XXCOUNTING_SORT
END SUBROUTINE Varradix
!***************************************************************************
! End of LSD sort with any Radix
!***************************************************************************
MODULE LEASTSIG
IMPLICIT NONE
!
! No Copyright is exerted due to considerable prior art in the Public Domain.
! This Fortran version by Peter Kelly ~ peter.kelly@acm.org
!
! Permission is hereby granted, free of charge, to any person obtaining
! a copy of this software and associated documentation files (the
! "Software"), to deal in the Software without restriction, including
! without limitation the rights to use, copy, modify, merge, publish,
! distribute, sublicense, and/or sell copies of the Software, and to
! permit persons to whom the Software is furnished to do so, subject to
! the following conditions:
! The above copyright notice and this permission notice shall be
! included in all copies or substantial portions of the Software.
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
! EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
! MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
! IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
! CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
! TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
! SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!
! Implementation of a classic Radix Sort LSD style :)
! Works well, Integers only but it goes faster than a comparison sort
CONTAINS
! Main Radix Sort sort function
SUBROUTINE LSDRADIXSORT(A , N)
IMPLICIT NONE
!
! Dummy arguments
!
INTEGER :: N
INTEGER , target, DIMENSION(0:N - 1) :: A ! All arrays based off zero, one day I'll fix it
INTENT (IN) N
INTENT (INOUT) A
!
! Local variables
!
INTEGER , DIMENSION(0:9) :: counts
INTEGER :: digitplace
INTEGER :: i
INTEGER :: j
INTEGER :: largestnum
INTEGER, DIMENSION(0:N - 1) :: results
!
digitplace = 1 ! Count of the keys
largestnum = MAXVAL(A)
DO WHILE ( (largestnum/digitplace)>0 )
counts = 0 ! Init the count array
DO i = 0 , N - 1 , 1
J = (A(i)/digitplace)
J = MODULO(j , 10)
counts(j) = counts(j) + 1
END DO
 
! Change count(i) so that count(i) now contains actual position of this digit in result()
! Working similar to the counting sort algorithm
DO i = 1 , 9 , 1
counts(i) = counts(i) + counts(i - 1) ! Build up the prefix sum
END DO
!
DO i = N - 1 , 0 , -1 ! Move from left to right
j = (A(i)/digitplace)
j = MODULO(j, 10)
results(counts(j) - 1) = A(i) ! Need to subtract one as we are zero based but prefix sum is 1 based
counts(j) = counts(j) - 1
END DO
!
DO i = 0 , N - 1 , 1 ! Copy the semi-sorted data into the input
A(i) = results(i)
END DO
!
digitplace = digitplace*10
END DO ! While loop
RETURN
END SUBROUTINE LSDRADIXSORT
END MODULE LEASTSIG
!***************************************************************************
! End of Classic LSD sort with Radix 10
!***************************************************************************
!Superfast FORTRAN LSD sort
! Dataset is input array, Scratch is working array
!
SUBROUTINE FASTLSDRAD(Dataset , Scratch , Dsize)
!
! No Copyright is exerted due to considerable prior art in the Public Domain.
! This Fortran version by Peter Kelly ~ peter.kelly@acm.org
!
! Permission is hereby granted, free of charge, to any person obtaining
! a copy of this software and associated documentation files (the
! "Software"), to deal in the Software without restriction, including
! without limitation the rights to use, copy, modify, merge, publish,
! distribute, sublicense, and/or sell copies of the Software, and to
! permit persons to whom the Software is furnished to do so, subject to
! the following conditions:
! The above copyright notice and this permission notice shall be
! included in all copies or substantial portions of the Software.
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
! EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
! MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
! IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
! CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
! TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
! SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!
! This LSD sort is optimized to a base 16,Radix 256 sort which is about as fast as LSD gets. As well as a fast
! algorithm, it has great cache coherency so performs exceptionally on large data sets,
! I have optimized out all the divide and modulus functions and replaced them with bit shifts for speed.
! A further speed optimization is obtained by using pointers to the DATA and TEMP arrays and swapping them each pass of
! the LSB calculation. In FORTRAN this is a bit clunky but much faster than copying data back and forth between arrays.
!
! All arrays are zero based as this makes the indexing calculations straightforward without the need for
! subsequent adds and subtracts to track the correct index
! .
IMPLICIT NONE
!
! Dummy arguments
!
INTEGER :: Dsize
INTEGER , TARGET , DIMENSION(0:Dsize - 1) :: Scratch ! Declared as TARGET as we will manipulate with pointers
INTEGER , TARGET , DIMENSION(0:Dsize - 1) :: Dataset
INTENT (IN) Dsize
INTENT (INOUT) Scratch , Dataset
!
! Local variables
!
INTEGER , POINTER , DIMENSION(:) :: a ! The pointer to the data
INTEGER , POINTER , DIMENSION(:) :: b ! The pointer to the buffer
INTEGER :: i
INTEGER :: j
INTEGER :: m
INTEGER , DIMENSION(0:255,0:3) :: stats_table
INTEGER :: n
LOGICAL :: swap
INTEGER :: u
!
stats_table = 0 ! index matrix
swap = .TRUE. ! For swapping pointers
!
a => Dataset
b => Scratch
!
DO i = 0 , Dsize - 1 , 1 ! generate histograms
u = a(i)
DO j = 0 , 3 , 1
n = IAND(u , z'FF')
u = SHIFTR(u , 8)
stats_table(n,j) = stats_table(n,j) + 1
END DO
END DO
!
DO i = 0 , 3 , 1 ! convert to indices
m = 0
DO j = 0 , 255 , 1
n = stats_table(j , i)
stats_table(j , i) = m
m = m + n
END DO
END DO
!
DO j = 0 , 3 , 1 ! Radix Sort, sort by LSB
DO i = 0 , Dsize - 1 , 1
u = a(i)
m = IAND(SHIFTR(u,SHIFTL(j,3)) , z'FF') ! Eliminate the MOD 16 and div with shifts
b(stats_table(m,j)) = u ! Push the data into the buffer
stats_table(m,j) = stats_table(m,j) + 1
END DO
!
! Instead of copying back from the temp values swap the array pointers
!
IF( swap )THEN
a => Scratch ! A now points to the b buffer
b => Dataset ! B now is the data set
ELSE
a => Dataset
b => Scratch
END IF
swap = .NOT.swap ! Set to swap back and forth every pass
END DO
!
RETURN
END SUBROUTINE FASTLSDRAD
!***************************************************************************
! End of Superfast LSD sort
!***************************************************************************
*=======================================================================
* RSORT - sort a list of integers by the Radix Sort algorithm
Line 858 ⟶ 2,021:
END IF
END ! of test program
</syntaxhighlight>
</lang>
 
{{out}}
Line 869 ⟶ 2,032:
=={{header|Go}}==
LSD radix 256, negatives handled by flipping the high bit.
<langsyntaxhighlight lang="go">package main
 
import (
Line 913 ⟶ 2,076:
}
fmt.Println("sorted: ", data)
}</langsyntaxhighlight>
Output:
<pre>
Line 922 ⟶ 2,085:
=={{header|Groovy}}==
This solution assumes the radix is a power of 2:
<langsyntaxhighlight lang="groovy">def radixSort = { final radixExponent, list ->
def fromBuckets = new TreeMap([0:list])
def toBuckets = new TreeMap()
Line 945 ⟶ 2,108:
final twosComplIndx = [] + (keys.findAll(neg)) + (keys.findAll(pos))
twosComplIndx.collect { fromBuckets[it] }.findAll { it != null }.flatten()
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println (radixSort(3, [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]))
println (radixSort(3, [88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))
println (radixSort(3, [23,-76,-990,580,97,57,350000,Long.MAX_VALUE,89,Long.MIN_VALUE,51,38,95*2**48,92,-24*2**48,46,31*2**32,24,14,12,57,78,4]))
Line 966 ⟶ 2,129:
println (radixSort(32, [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]))
println (radixSort(32, [88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))
println (radixSort(32, [23,-76,-990,580,97,57,350000,Long.MAX_VALUE,89,Long.MIN_VALUE,51,38,95*2**48,92,-24*2**48,46,31*2**32,24,14,12,57,78,4]))</langsyntaxhighlight>
 
Output:
<pre>
<pre style="height:30ex;overflow:scroll;">..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................[4, 12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99]
..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................[4, 12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99]
..........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................[0, 1, 4, 5, 7, 8, 12, 14, 18, 20, 31, 33, 44, 62, 70, 73, 75, 76, 78, 81, 82, 84, 88]
..........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................[-9223372036854775808, -6755399441055744, -990, -76, 4, 12, 14, 23, 24, 38, 46, 51, 57, 57, 78, 89, 92, 97, 580, 350000, 133143986176, 26740122787512320, 9223372036854775807]
Line 991 ⟶ 2,155:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Data.Bits (Bits(testBit, bitSize))
import Data.List (partition)
 
Line 1,012 ⟶ 2,176:
aux (-1) list = list
aux bit list = aux (bit - 1) lower ++ aux (bit - 1) upper where
(lower, upper) = partition (not . flip testBit bit) list</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,019 ⟶ 2,183:
contains a subtle inefficiency: subscripting a numeric value first coerces it into a string.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
every writes((!rSort(A)||" ")|"\n")
end
Line 1,032 ⟶ 2,196:
}
return A
end</langsyntaxhighlight>
 
Sample run:
Line 1,046 ⟶ 2,210:
<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>.
 
<syntaxhighlight lang="j">
<lang j>
radixSortR =: 3 : 0 NB. base radixSort data
16 radixSortR y
Line 1,057 ⟶ 2,221:
end.
x#.keys NB. restore the data
)</langsyntaxhighlight>
 
An alternate implementation is
<langsyntaxhighlight lang="j">radixsort=: (] #~ [: +/ =/) i.@(>./)</langsyntaxhighlight>
 
This uses the maximum value of the list for the base, which allows the list to be sorted in one pass.
Line 1,066 ⟶ 2,230:
Example use:
 
<langsyntaxhighlight lang="j"> radixsort ?.@#~10
4 5 6 6 6 6 6 8 8</langsyntaxhighlight>
 
Or, for negative number support:
 
<langsyntaxhighlight lang="j">rsort=: (] + radixsort@:-) <./</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="j"> rsort _6+?.@#~10
_2 _1 0 0 0 0 0 2 2</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public static int[] sort(int[] old) {
// Loop for every bit in the integers
for (int shift = Integer.SIZE - 1; shift > -1; shift--) {
Line 1,112 ⟶ 2,276:
 
return old;
}</langsyntaxhighlight>
 
{{trans|NetRexx}}
<syntaxhighlight lang="java">
<lang Java>
import java.util.ArrayList;
import java.util.Arrays;
Line 1,234 ⟶ 2,398:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,260 ⟶ 2,424:
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq"># Sort the input array;
# "base" must be an integer greater than 1
def radix_sort(base):
Line 1,283 ⟶ 2,447:
def radix_sort:
radix_sort(10);
</syntaxhighlight>
</lang>
'''Example'''
<syntaxhighlight lang="jq">
<lang jq>
# Verify that radix_sort agrees with sort
( [1, 3, 8, 9, 0, 0, 8, 7, 1, 6],
Line 1,291 ⟶ 2,455:
[170, 45, 75, 90, 2, 24, -802, -66] )
| (radix_sort == sort)
</syntaxhighlight>
</lang>
{{Out}}
true
true
true
 
 
=={{header|Julia}}==
{{trans|Scala}}
<langsyntaxhighlight lang="julia">function radixsort(tobesorted::Vector{Int64})
arr = deepcopy(tobesorted)
for shift in 63:-1:0
Line 1,327 ⟶ 2,490:
 
testradixsort()
</langsyntaxhighlight>{{output}}<pre>
[-802, -90, 2, 24, 45, 66, 75, 170]
[-1837, -990, -26, -4, 5, 58, 331, 331, 990, 2028]
Line 1,334 ⟶ 2,497:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun radixSort(original: IntArray): IntArray {
Line 1,369 ⟶ 2,532:
)
for (array in arrays) println(radixSort(array).contentToString())
}</langsyntaxhighlight>
 
{{out}}
Line 1,377 ⟶ 2,540:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[SortByPos, RadixSort]
SortByPos[data : {_List ..}, pos_Integer] := Module[{digs, order},
digs = data[[All, pos]];
Line 1,394 ⟶ 2,557:
digs += offset;
digs
]</langsyntaxhighlight>
Testing out the algorithm:
<langsyntaxhighlight Mathematicalang="mathematica">RadixSort[{170,45,75,-90,-802,24,2,66}]
RadixSort[{170,45,75,90,802,2,24,66}]</langsyntaxhighlight>
{{out}}
<pre>{-802,-90,2,24,45,66,75,170}
{2,24,45,66,75,90,170,802}</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">func radixSort[T](a: openArray[T]): seq[T] =
 
result = @a
 
## Loop for every bit in the integers.
for shift in countdown(63, 0):
var tmp = newSeq[T](result.len) # The array to put the partially sorted array into.
var j = 0 # The number of 0s.
for i in 0..result.high:
# If there is a 1 in the bit we are testing, the number will be negative.
let move = result[i] shl shift >= 0
# If this is the last bit, negative numbers are actually lower.
let toBeMoved = if shift == 0: not move else: move
if toBeMoved:
tmp[j] = result[i]
inc j
else:
# It's a 1, so stick it in the result array for now.
result[i - j] = result[i]
# Copy over the 1s from the old array.
for i in j..tmp.high:
tmp[i] = result[i - j]
# And now the tmp array gets switched for another round of sorting.
result =move(tmp)
 
 
when isMainModule:
 
const arrays = [@[170, 45, 75, -90, -802, 24, 2, 66],
@[-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028]]
 
for a in arrays:
echo radixSort(a)</syntaxhighlight>
 
{{out}}
<pre>@[-802, -90, 2, 24, 45, 66, 75, 170]
@[-1837, -990, -26, -4, 5, 58, 331, 331, 990, 2028]</pre>
 
=={{header|NetRexx}}==
Line 1,408 ⟶ 2,610:
Limitations - Handles decimal digits only.
===Using the <tt>Rexx</tt> class===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,480 ⟶ 2,682:
end il
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,511 ⟶ 2,713:
</pre>
===Using <tt>Collection</tt> classes===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,597 ⟶ 2,799:
end il
return
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Radix sort in base 10.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 1,633 ⟶ 2,835:
$_ = 0 + $_ for @return; # Remove zeros.
return @return;
}</langsyntaxhighlight>
To test, add the following lines:
<langsyntaxhighlight lang="perl">use Test::More tests => 1000;
 
for (1 .. 1000) {
my @l = map int rand(2000) - 1000, 0 .. 20;
is_deeply([radix(@l)], [sort { $a <=> $b } @l]);
}</langsyntaxhighlight>
 
=={{header|Perl 6}}==
A base-10 radix sort, done on the string representation of the integers. Signs are handled by in-place reversal of the '-' bucket on the last iteration. (The sort in there is not cheating; it only makes sure we process the buckets in the right order, since <tt>classify</tt> might return the buckets in random order. It might be more efficient to create our own ordered buckets, but this is succinct.)
<lang perl6>sub radsort (@ints) {
my $maxlen = max @ints».chars;
my @list = @ints».fmt("\%0{$maxlen}d");
 
for reverse ^$maxlen -> $r {
my @buckets = @list.classify( *.substr($r,1) ).sort: *.key;
@buckets[0].value = @buckets[0].value.reverse.List
if !$r and @buckets[0].key eq '-';
@list = flat map *.value.values, @buckets;
}
@list».Int;
}
 
.say for radsort (-2_000 .. 2_000).roll(20);</lang>
{{out}}
<pre>-1585
-1427
-1228
-1067
-945
-657
-643
-232
-179
-28
37
411
488
509
716
724
1504
1801
1864
1939</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function radixSortn(sequence s, integer n)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence buckets = repeat({},10)
sequence res = {}
<span style="color: #008080;">function</span> <span style="color: #000000;">radixSortn</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">buckets</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">({},</span><span style="color: #000000;">10</span><span style="color: #0000FF;">),</span>
integer digit = remainder(floor(s[i]/power(10,n-1)),10)+1
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
buckets[digit] = append(buckets[digit],s[i])
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #004080;">integer</span> <span style="color: #000000;">digit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]/</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span>
for i=1 to length(buckets) do
<span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">digit</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">digit</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
integer len = length(buckets[i])
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if len!=0 then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if len=1 or n=1 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
res &= buckets[i]
<span style="color: #008080;">if</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
else
<span style="color: #008080;">if</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">or</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
res &= radixSortn(buckets[i],n-1)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
end if
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">radixSortn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
function split_by_sign(sequence s)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence buckets = {{},{}}
for i=1 to length(s) do
<span style="color: #008080;">function</span> <span style="color: #000000;">split_by_sign</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
integer si = s[i]
<span style="color: #004080;">sequence</span> <span style="color: #000000;">buckets</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{},{}}</span>
if si<0 then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
buckets[1] = append(buckets[1],-si)
<span style="color: #004080;">integer</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
else
<span style="color: #008080;">if</span> <span style="color: #000000;">si</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
buckets[2] = append(buckets[2],si)
<span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],-</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">else</span>
end for
<span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">],</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)</span>
return buckets
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">return</span> <span style="color: #000000;">buckets</span>
function radixSort(sequence s)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
integer mins = min(s)
integer passes = max(max(s),abs(mins))
<span style="color: #008080;">function</span> <span style="color: #000000;">radixSort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
passes = floor(log10(passes))+1
<span style="color: #004080;">integer</span> <span style="color: #000000;">mins</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span>
if mins<0 then
<span style="color: #000000;">passes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mins</span><span style="color: #0000FF;">))</span>
sequence buckets = split_by_sign(s)
<span style="color: #000000;">passes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">log10</span><span style="color: #0000FF;">(</span><span style="color: #000000;">passes</span><span style="color: #0000FF;">))+</span><span style="color: #000000;">1</span>
buckets[1] = reverse(sq_uminus(radixSortn(buckets[1],passes)))
<span style="color: #008080;">if</span> <span style="color: #000000;">mins</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
buckets[2] = radixSortn(buckets[2],passes)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">buckets</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">split_by_sign</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
s = buckets[1]&buckets[2]
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_uminus</span><span style="color: #0000FF;">(</span><span style="color: #000000;">radixSortn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">passes</span><span style="color: #0000FF;">)))</span>
else
<span style="color: #0000FF;">&</span> <span style="color: #000000;">radixSortn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buckets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">],</span><span style="color: #000000;">passes</span><span style="color: #0000FF;">)</span>
s = radixSortn(s,passes)
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">radixSortn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">passes</span><span style="color: #0000FF;">)</span>
return s
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?radixSort({1, 3, 8, 9, 0, 0, 8, 7, 1, 6})
?radixSort({170, 45, 75, 90, 2, 24, 802, 66})
<span style="color: #0000FF;">?</span><span style="color: #000000;">radixSort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">})</span>
?radixSort({170, 45, 75, 90, 2, 24, -802, -66})
<span style="color: #0000FF;">?</span><span style="color: #000000;">radixSort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">170</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">45</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">75</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">90</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">24</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">802</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">66</span><span style="color: #0000FF;">})</span>
?radixSort({100000, -10000, 400, 23, 10000})</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">radixSort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">170</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">45</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">75</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">90</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">24</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">802</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">66</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">radixSort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">100000</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">400</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">23</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10000</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,743 ⟶ 2,910:
=={{header|PicoLisp}}==
This is a LSD base-2 radix sort using queues:
<langsyntaxhighlight PicoLisplang="picolisp">(de radixSort (Lst)
(let Mask 1
(while
Line 1,757 ⟶ 2,924:
Mask (* 2 Mask) )
Flg ) ) )
Lst )</langsyntaxhighlight>
Output:
<pre>: (radixSort (make (do 12 (link (rand -999 999)))))
Line 1,763 ⟶ 2,930:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Structure bucket
List i.i()
EndStructure
Line 1,848 ⟶ 3,015:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>0, 0, 1, 1, 3, 6, 7, 8, 8, 9
Line 1,859 ⟶ 3,026:
This is the Wikipedia example code extended with an extra pass to sort negative values correctly.
 
<langsyntaxhighlight lang="python">#python2.6 <
from math import log
Line 1,906 ⟶ 3,073:
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list))
</syntaxhighlight>
</lang>
 
An alternate implementation using which works on Python 3:
 
<langsyntaxhighlight lang="python">#python3.7 <
def flatten(some_list):
"""
Line 1,970 ⟶ 3,137:
result = []
for b in bins:
#If the bin is empty it skips the recursive call
if b == []:
continue
# Make the recursive call
# Sort each of the sub-lists in our bins
Line 1,980 ⟶ 3,150:
 
return flattened_result
</syntaxhighlight>
</lang>
 
That same example but more compact:
 
<langsyntaxhighlight lang="python">#python3.7 <
def flatten(l):
return [y for x in l for y in x]
Line 2,004 ⟶ 3,174:
bins[int(str(e).zfill(s)[i])] += [e]
 
return flatten([radix(b, p-1, s) for b in bins])
</syntaxhighlight>
</lang>
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>
#lang QB64
'* don't be an a$$. Keep this credit notice with the source:
Line 2,313 ⟶ 3,483:
END SELECT
END SUB
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ stack ] is digit ( --> s )
 
[ behead swap witheach min ] is smallest ( [ --> n )
 
[ [] over smallest
rot witheach
[ over -
rot swap join swap ]
swap
0 digit put
dup size temp put
[ ' [ [ ] ] 16 of
constant
swap witheach
[ dup dip
[ digit share
>> 15 &
2dup peek ]
join
unrot poke ]
dup 0 peek size
temp share != while
behead swap
witheach join
4 digit tally again ]
behead nip
temp release
digit release
[] unrot
witheach
[ over +
rot swap join swap ]
drop ] is radixsort ( [ --> [ )
 
[] 256 times
[ 1999 random 999 - join ]
radixsort
16 times
[ 16 times
[ behead
dup 0 > if sp
dup abs dup
10 < if sp
100 < if sp
echo sp ] cr ]
drop</syntaxhighlight>
 
{{out}}
 
<pre>-992 -984 -982 -962 -957 -952 -921 -907 -906 -906 -903 -874 -870 -864 -861 -858
-852 -852 -844 -836 -835 -823 -804 -804 -802 -800 -794 -791 -789 -786 -778 -770
-766 -759 -754 -752 -744 -743 -743 -718 -716 -695 -685 -683 -680 -677 -672 -670
-669 -644 -643 -640 -639 -639 -623 -603 -601 -589 -588 -575 -572 -567 -565 -557
-554 -542 -535 -531 -527 -518 -515 -501 -475 -474 -457 -420 -411 -386 -377 -376
-371 -367 -350 -348 -347 -346 -332 -314 -301 -301 -299 -293 -285 -272 -242 -239
-237 -234 -230 -225 -225 -196 -188 -163 -147 -146 -145 -143 -125 -121 -119 -116
-110 -108 -105 -104 -97 -85 -71 -69 -66 -58 -52 -40 -25 -9 -8 14
23 44 45 49 67 69 83 87 87 127 138 143 145 159 160 166
168 169 178 187 204 218 220 231 231 232 235 237 244 251 255 258
264 265 272 285 287 300 314 337 341 348 351 353 359 367 370 372
376 398 402 410 415 420 443 464 465 474 479 483 516 519 520 541
543 546 552 558 559 561 565 579 596 607 616 637 668 668 679 682
698 698 714 720 728 734 736 744 768 768 789 789 797 797 799 802
802 814 815 815 819 833 841 844 848 862 868 885 887 890 894 906
912 927 930 933 936 946 947 950 955 963 967 968 969 969 989 999
</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang Racket
(define (radix-sort l r)
Line 2,342 ⟶ 3,581:
(sorted? (radix-sort (make-random-list) (+ 2 (random 98)))))
;; => #t, so all passed
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
A base-10 radix sort, done on the string representation of the integers. Signs are handled by in-place reversal of the '-' bucket on the last iteration. (The sort in there is not cheating; it only makes sure we process the buckets in the right order, since <tt>classify</tt> might return the buckets in random order. It might be more efficient to create our own ordered buckets, but this is succinct.)
<syntaxhighlight lang="raku" line>sub radsort (@ints) {
my $maxlen = max @ints».chars;
my @list = @ints».fmt("\%0{$maxlen}d");
 
for reverse ^$maxlen -> $r {
my @buckets = @list.classify( *.substr($r,1) ).sort: *.key;
@buckets[0].value = @buckets[0].value.reverse.List
if !$r and @buckets[0].key eq '-';
@list = flat map *.value.values, @buckets;
}
@list».Int;
}
 
.say for radsort (-2_000 .. 2_000).roll(20);</syntaxhighlight>
{{out}}
<pre>-1585
-1427
-1228
-1067
-945
-657
-643
-232
-179
-28
37
411
488
509
716
724
1504
1801
1864
1939</pre>
 
=={{header|REXX}}==
This REXX version also works with malformed integers. &nbsp; &nbsp; &nbsp; '''7''', &nbsp; '''007''', &nbsp; '''+7''', &nbsp; '''.7e1''', &nbsp; '''7.0''' &nbsp; are all treated as equal.
<langsyntaxhighlight lang="rexx">/*REXX program performs a radix sort on an integer array (can be negative/zero/positive)*/
call gen /*call subroutine to generate numbers. */
call radSort n, w /*invoke the radix sort subroutine. */
call show do j=1 for n; say 'item' right(j, w) "after the radix sort:" right( /*display the elements in the @.j, w) array*/
exit 0 end /*j*/ /*stick [↑]a fork displayin sortedit, items ───►we're termall done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: ILF= 0 2 3 4 5 5 7. 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15 ,
Line 2,363 ⟶ 3,640:
end /*m*/; return /*W: is the maximum width ↑ of numbers*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
radSort: procedure expose @. w; parse arg size,w; mote= c2d(' '); #= 1; !.#._n= size
!.#._b= 1; if w=='' then w= 8
!.#._b=1;
!.#._i= 1; do i=1 for size; y=@.i; @.i= right(abs(y), w, 0); if y<0 then @.i= '-'@.i
end /*i*/ /* [↑] negative case.*/
 
do while #\==0; ctr.= 0; L= 'ffff'x; low= !.#._b; n= !.#._n; $= !.#._i; H=
#= #-1 /* [↑] is the radix. */
do j=low for n; parse var @.j =($) _ +1; ctr._= ctr._ + 1
if ctr._==1 & _\=='' then do; if _<<L then L=_; if _>>H then H=_
end /* ↑↑ */
Line 2,380 ⟶ 3,657:
L= c2d(L); H= c2d(H); ?= ctr._ + low; top._= ?; ts= mote
max= L
do k=L to H; _= d2c(k, 1); c= ctr._ /* [↓] swap 2 item radices.*/
if c>ts then parse value c k with ts max; ?= ?+c; top._= ?
end /*k*/
Line 2,389 ⟶ 3,666:
if piv>=c then leave; top._= c; ?= @.c; @.c= it; it= ?
end /*forever*/
top._= piv; @.piv= it; piv= piv + ctr._
end /*while piv<low+n */
i= max
Line 2,405 ⟶ 3,682:
end /*while #\==0 */
#= 0 /* [↓↓↓] handle neg. and pos. arrays. */
do i=size by -1 tofor 1size; if @.i>=0 then iterate; #= #+1; @@.#= @.i
end /*i*/
do j=1 for size; if @.j>=0 then do; #= #+1; @@.#= @.j; end; @.j= @@.j+0
end /*j*/; return /* [↑↑↑] combine 2 lists into 1 list. */</lang>
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do j=1 for n; say 'item' right(j, w) "after the radix sort:" right(@.j, w)
end /*j*/; return /* [↑] display sorted items ───► term.*/</syntaxhighlight>
{{out|output|text=&nbsp; &nbsp; (with the middle section elided.)}}
 
Line 2,460 ⟶ 3,741:
=={{header|Ruby}}==
Negative number handling courtesy the Tcl solution.
<langsyntaxhighlight lang="ruby">class Array
def radix_sort(base=10)
ary = dup
Line 2,485 ⟶ 3,766:
p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort
p [170, 45, 75, 90, 2, 24, -802, -66].radix_sort
p [100000, -10000, 400, 23, 10000].radix_sort</langsyntaxhighlight>
running with $DEBUG on produces:
<pre>[0, [0, 0, 1, 1, 3, 6, 7, 8, 8, 9]]
Line 2,506 ⟶ 3,787:
 
another version (After sorting at the absolute value, it makes a negative order reverse.)
<langsyntaxhighlight lang="ruby">class Array
def radix_sort(base=10)
ary = dup
Line 2,518 ⟶ 3,799:
ary.partition{|n| n<0}.inject{|minus,plus| minus.reverse + plus}
end
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) {
let (left, right) = out.split_at_mut(in1.len());
left.clone_from_slice(in1);
right.clone_from_slice(in2);
}
 
// least significant digit radix sort
fn radix_sort(data: &mut [i32]) {
for bit in 0..31 {
// types of small and big is Vec<i32>.
// It will be infered from the next call of merge function.
let (small, big): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| (x >> bit) & 1 == 0);
merge(&small, &big, data);
}
// last bit is sign
let (negative, positive): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| x < 0);
merge(&negative, &positive, data);
}
 
fn main() {
let mut data = [170, 45, 75, -90, -802, 24, 2, 66, -17, 2];
println!("Before: {:?}", data);
radix_sort(&mut data);
println!("After: {:?}", data);
}
</syntaxhighlight>
{{out}}
<pre>
Before: [170, 45, 75, -90, -802, 24, 2, 66, -17, 2]
After: [-802, -90, -17, 2, 2, 24, 45, 66, 75, 170]
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object RadixSort extends App {
def sort(toBeSort: Array[Int]): Array[Int] = { // Loop for every bit in the integers
var arr = toBeSort
Line 2,545 ⟶ 3,861:
 
println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", "))
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
 
===An implementation for non-negative integers only===
{{works with|R7RS}}
 
 
<syntaxhighlight lang="scheme">;;; An illustrative implementation of the radix-10 example at
;;; https://en.wikipedia.org/w/index.php?title=Radix_sort&oldid=1070890278#Least_significant_digit
 
(cond-expand
(r7rs)
(chicken (import (r7rs))))
 
(import (scheme base))
(import (scheme write))
 
(define (sort-by-decimal-digit data power-of-10)
(define bins (make-vector 10 '()))
(do ((i (- (vector-length data) 1) (- i 1)))
((= i -1))
(let* ((element (vector-ref data i))
(digit (truncate-remainder
(truncate-quotient element power-of-10)
10)))
(vector-set! bins digit
(cons element (vector-ref bins digit)))))
(let ((non-zero-found
(let loop ((i 1))
(cond ((= i (vector-length bins)) #f)
((pair? (vector-ref bins i)) #t)
(else (loop (+ i 1)))))))
(when non-zero-found
(let ((i 0))
(do ((j 0 (+ j 1)))
((= j (vector-length bins)))
(do ((p (vector-ref bins j) (cdr p)))
((null? p))
(vector-set! data i (car p))
(set! i (+ i 1))))))
(not non-zero-found)))
 
(define (radix-sort data)
(let loop ((power-of-10 1))
(let ((done (sort-by-decimal-digit data power-of-10)))
(unless done
(loop (* 10 power-of-10))))))
 
(define data (vector-copy #(170 45 75 90 2 802 2 66)))
(write data)
(newline)
(radix-sort data)
(write data)
(newline)</syntaxhighlight>
 
{{out}}
<pre>$ gosh radix_sort_task.scm
#(170 45 75 90 2 802 2 66)
#(2 2 45 66 75 90 170 802)</pre>
 
===An implementation using lexicographic order to support negative integers===
{{works with|R7RS}}
 
 
The following implementation converts signed integers to a lexicographically ordered representation (specifically, unsigned numbers in the correct order). It then sorts the lexicographically ordered representation, and finally converts back to the original representation.
 
<syntaxhighlight lang="scheme">;;; An illustrative implementation of the radix-10 example at
;;; https://en.wikipedia.org/w/index.php?title=Radix_sort&oldid=1070890278#Least_significant_digit
 
(cond-expand
(r7rs)
(chicken (import (r7rs))))
 
(import (scheme base))
(import (scheme write))
 
(define (sort-by-decimal-digit data power-of-10)
(define bins (make-vector 10 '()))
(do ((i (- (vector-length data) 1) (- i 1)))
((= i -1))
(let* ((element (vector-ref data i))
(digit (truncate-remainder
(truncate-quotient element power-of-10)
10)))
(vector-set! bins digit
(cons element (vector-ref bins digit)))))
(let ((non-zero-found
(let loop ((i 1))
(cond ((= i (vector-length bins)) #f)
((pair? (vector-ref bins i)) #t)
(else (loop (+ i 1)))))))
(when non-zero-found
(let ((i 0))
(do ((j 0 (+ j 1)))
((= j (vector-length bins)))
(do ((p (vector-ref bins j) (cdr p)))
((null? p))
(vector-set! data i (car p))
(set! i (+ i 1))))))
(not non-zero-found)))
 
(define (radix-sort data)
(define offset 0)
 
(do ((i 0 (+ i 1)))
((<= (vector-length data) i))
(let ((x (vector-ref data i)))
(when (negative? x)
(set! offset (max offset (- x))))))
 
(do ((i 0 (+ i 1)))
((= i (vector-length data)))
(vector-set! data i (+ (vector-ref data i) offset)))
 
(let loop ((power-of-10 1))
(let ((done (sort-by-decimal-digit data power-of-10)))
(unless done
(loop (* 10 power-of-10)))))
 
(do ((i 0 (+ i 1)))
((= i (vector-length data)))
(let ((x (vector-ref data i)))
(vector-set! data i (- (vector-ref data i) offset)))))
 
(define data (vector-copy #(170 45 75 90 2 802 2 66)))
(write data)
(newline)
(radix-sort data)
(write data)
(newline)
 
(newline)
(set! data (vector-copy #(170 -45 75 -90 2 -802 2 -66)))
(write data)
(newline)
(radix-sort data)
(write data)
(newline)</syntaxhighlight>
 
{{out}}
<pre>$ chibi radix_sort_task-2.scm
#(170 45 75 90 2 802 2 66)
#(2 2 45 66 75 90 170 802)
 
#(170 -45 75 -90 2 -802 2 -66)
#(-802 -90 -66 -45 2 2 75 170)</pre>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">class Array {
method radix_sort(base=10) {
var arr = self.clone
Line 2,574 ⟶ 4,036:
] {
say arr.radix_sort
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,584 ⟶ 4,046:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates radixsort@&{base:}
sink bucketize
def value: $;
$::raw ~/ $@radixsort.digit::raw -> #
when <=0 ?($value::raw <0..>)> do
..|@radixsort.positives: $value;
when <=0> do
..|@radixsort.negatives(-1last): $value;
<>otherwise
def bucket: $ mod $base -> \(<?($value<0..>)> $ + 1 ! <=0> $base ! <> $ !\);
..|@radixsort.buckets($bucket): $value;
@radixsort.done: 0;
Line 2,602 ⟶ 4,064:
$... -> !bucketize
$@.done -> #
when <=done´1> do
[$@.negatives(-1last..1:-1)... ..., $@.positives...] !
otherwise
<>
def previous: $@.buckets;
..|@: {done: 1, digit: $@.digit::raw * $base, buckets:[1..$base -> []]};
..|@.negatives: [];
$previous... ... -> !bucketize
Line 2,612 ⟶ 4,074:
end radixsort
 
[170, 45, 75, 91, 90, 92, 802, 24, 2, 66] -> radixsort@&{base:10} -> !OUT::write
'
' -> !OUT::write
[-170, -45, -91, -90, -92, -802, -24, -2, -76] -> radixsort@&{base:10} -> !OUT::write
'
' -> !OUT::write
[170, 45, 75, -91, -90, -92, -802, 24, 2, 66] -> radixsort@&{base:10} -> !OUT::write
'
' -> !OUT::write
[170, 45, 75, -91, -90, -92, -802, 24, 2, 66] -> radixsort@&{base:3} -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,633 ⟶ 4,095:
=={{header|Tcl}}==
{{trans|Python}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc splitByRadix {lst base power} {
# create a list of empty lists to hold the split by digit
Line 2,665 ⟶ 4,127:
}
return $lst
}</langsyntaxhighlight>
Demonstrations:
<langsyntaxhighlight lang="tcl">puts [radixSort {1 3 8 9 0 0 8 7 1 6}]
puts [radixSort {170 45 75 90 2 24 802 66}]
puts [radixSort {170 45 75 90 2 24 -802 -66}]</langsyntaxhighlight>
Output:
<pre>
Line 2,675 ⟶ 4,137:
2 24 45 66 75 90 170 802
-802 -66 2 24 45 75 90 170
</pre>
 
=={{header|uBasic/4tH}}==
{{Trans|BBC BASIC}}
In uBasic/4tH you can't pass an array as a parameter. All arrays are global.
<syntaxhighlight lang="qbasic">Dim @t(10)
 
Push 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
 
For i = 0 Step 1 While Used()
@t(i) = Pop()
Next
 
Proc _Radixsort(10, 10)
 
For i = 0 TO 9
Print @t(i),
Next
 
Print
End
_Radixsort
Param (2)
Local (5)
Dim @b(a@)
Dim @u(b@)
 
For e@ = 0 TO a@-1
If @t(e@) < f@ Then f@ = @t(e@)
If @t(e@) > g@ Then g@ = @t(e@)
Next
For e@ = 0 To a@-1 : @t(e@) = @t(e@) - f@ : Next
g@ = g@ - f@
d@ = 1
Do While g@ / d@
For e@ = 0 to a@-1 : @u(e@) = 0 : Next
For e@ = 0 TO a@-1
@u(@t(e@) / d@ % b@) = @u(@t(e@) / d@ % b@) + 1
Next
For e@ = 1 TO b@-1
@u(e@) = @u(e@) + @u(e@ - 1)
Next
For e@ = a@-1 TO 0 Step -1
c@ = @t(e@) / d@ % b@
@u(c@) = @u(c@)-1
@b(@u(c@)) = @t(e@)
Next
For e@ = 0 To a@-1 : @t(e@) = @b(e@) : Next
d@ = d@ * b@
Loop
For e@ = 0 To a@-1 : @t(e@) = @t(e@) + f@ : Next
Return</syntaxhighlight>
{{Out}}
<pre>-31 0 1 2 2 4 65 83 99 782
 
0 OK, 0:177</pre>
=={{header|Wren}}==
This is based on the approach used [https://www.geeksforgeeks.org/radix-sort/ here] which I've adjusted to deal with negative elements.
<syntaxhighlight lang="wren">// counting sort of 'a' according to the digit represented by 'exp'
var countSort = Fn.new { |a, exp|
var n = a.count
var output = [0] * n
var count = [0] * 10
for (i in 0...n) {
var t = (a[i]/exp).truncate % 10
count[t] = count[t] + 1
}
for (i in 1..9) count[i] = count[i] + count[i-1]
for (i in n-1..0) {
var t = (a[i]/exp).truncate % 10
output[count[t] - 1] = a[i]
count[t] = count[t] - 1
}
for (i in 0...n) a[i] = output[i]
}
 
// sorts 'a' in place
var radixSort = Fn.new { |a|
// check for negative elements
var min = a.reduce { |m, i| (i < m) ? i : m }
// if there are any, increase all elements by -min
if (min < 0) (0...a.count).each { |i| a[i] = a[i] - min }
// now get the maximum to know number of digits
var max = a.reduce { |m, i| (i > m) ? i : m }
// do counting sort for each digit
var exp = 1
while ((max/exp).truncate > 0) {
countSort.call(a, exp)
exp = exp * 10
}
// if there were negative elements, reduce all elements by -min
if (min < 0) (0...a.count).each { |i| a[i] = a[i] + min }
}
 
var aa = [[4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [170, 45, 75, 90, 2, 24, -802, -66]]
for (a in aa) {
System.print("Unsorted: %(a)")
radixSort.call(a)
System.print("Sorted : %(a)\n")
}</syntaxhighlight>
 
{{out}}
<pre>
Unsorted: [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
Sorted : [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
 
Unsorted: [170, 45, 75, 90, 2, 24, -802, -66]
Sorted : [-802, -66, 2, 24, 45, 75, 90, 170]
</pre>
 
=={{header|zkl}}==
In place int sort, fairly light on garbage creation.
<langsyntaxhighlight lang="zkl">fcn radixSort(ns){ // ints only, inplace, ns is mutable
b:=(0).pump(20,List,List().copy); // 20 [empty] buckets: -10..10
z:=ns.reduce(fcn(a,b){ a.abs().max(b.abs()) },0); // |max or min of input|
Line 2,690 ⟶ 4,269:
}
ns
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">radixSort(T(170, 45, 75, 90, 802, 2, 24, 66)).println();
radixSort(T(170, 45, 75, -90, -802, 24, 2, 66)).println();</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user