Sorting algorithms/Radix sort: Difference between revisions

Content added Content deleted
(→‎{{header|Tailspin}}: update to stricter typing)
m (syntax highlighting fixup automation)
Line 12: Line 12:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F flatten(some_list)
<syntaxhighlight lang="11l">F flatten(some_list)
[Int] new_list
[Int] new_list
L(sub_list) some_list
L(sub_list) some_list
Line 36: Line 36:


V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
print(radix_sort(arr))</lang>
print(radix_sort(arr))</syntaxhighlight>


{{out}}
{{out}}
Line 45: Line 45:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program radixSort64.s */
/* program radixSort64.s */
Line 214: Line 214:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Value : -154389710
Value : -154389710
Line 234: Line 234:


radix_sort.adb:
radix_sort.adb:
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
procedure Radix_Sort is
procedure Radix_Sort is
type Integer_Array is array (Positive range <>) of Integer;
type Integer_Array is array (Positive range <>) of Integer;
Line 316: Line 316:
end loop;
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.New_Line;
end Radix_Sort;</lang>
end Radix_Sort;</syntaxhighlight>


output:
output:
Line 322: Line 322:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>PROC radixsort = (REF []INT array) VOID:
<syntaxhighlight lang="algol68">PROC radixsort = (REF []INT array) VOID:
(
(
[UPB array]INT zero;
[UPB array]INT zero;
Line 371: Line 371:
radixsort(a);
radixsort(a);
print(("After: ", a))
print(("After: ", a))
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 380: Line 380:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program radixSort1.s */
/* program radixSort1.s */
Line 544: Line 544:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Value : -25000
Value : -25000
Line 563: Line 563:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>radixSort: function [items][
<syntaxhighlight lang="rebol">radixSort: function [items][
base: 10
base: 10
a: new items
a: new items
Line 581: Line 581:
]
]


print radixSort [3 1 2 8 5 7 9 4 6]</lang>
print radixSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>


{{out}}
{{out}}
Line 589: Line 589:
=={{header|ATS}}==
=={{header|ATS}}==


<lang ats>(*
<syntaxhighlight lang="ats">(*
Stable integer-keyed radix sorts for unsigned and signed integers
Stable integer-keyed radix sorts for unsigned and signed integers
of the various typekinds.
of the various typekinds.
Line 982: Line 982:
end
end


(*------------------------------------------------------------------*)</lang>
(*------------------------------------------------------------------*)</syntaxhighlight>


{{out}}
{{out}}
Line 989: Line 989:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Radix_Sort(data){
<syntaxhighlight lang="autohotkey">Radix_Sort(data){
loop, parse, data, `,
loop, parse, data, `,
n := StrLen(A_LoopField)>n?StrLen(A_LoopField):n
n := StrLen(A_LoopField)>n?StrLen(A_LoopField):n
Line 1,001: Line 1,001:
}
}
return data
return data
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>d = 170,45,75,90,802,2,24,66
Examples:<syntaxhighlight lang="autohotkey">d = 170,45,75,90,802,2,24,66
MsgBox, 262144, , % Radix_Sort(d)</lang>
MsgBox, 262144, , % Radix_Sort(d)</syntaxhighlight>
Outputs:<pre>2,24,45,66,75,90,170,802</pre>
Outputs:<pre>2,24,45,66,75,90,170,802</pre>


=={{header|B4X}}==
=={{header|B4X}}==
<lang b4x>Sub RadixSort (Old() As Int)
<syntaxhighlight lang="b4x">Sub RadixSort (Old() As Int)
Dim i, j As Int
Dim i, j As Int
Dim tmp(Old.Length) As Int
Dim tmp(Old.Length) As Int
Line 1,031: Line 1,031:
Log(i)
Log(i)
Next
Next
End Sub</lang>
End Sub</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 1,045: Line 1,045:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
The array index is assumed to start at zero. The third parameter of PROCradixsort() is the radix used.
The array index is assumed to start at zero. The third parameter of PROCradixsort() is the radix used.
<lang bbcbasic> DIM test%(9)
<syntaxhighlight lang="bbcbasic"> DIM test%(9)
test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCradixsort(test%(), 10, 10)
PROCradixsort(test%(), 10, 10)
Line 1,081: Line 1,081:
ENDWHILE
ENDWHILE
a%() += l%
a%() += l%
ENDPROC</lang>
ENDPROC</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 1,088: Line 1,088:


=={{header|C}}==
=={{header|C}}==
Radix sort, "digits" are most significant bits.<lang c>#include <stdio.h>
Radix sort, "digits" are most significant bits.<syntaxhighlight lang="c">#include <stdio.h>
#include <limits.h>
#include <limits.h>
#include <stdlib.h>
#include <stdlib.h>
Line 1,153: Line 1,153:
for (size_t i = 0; i < ARR_LEN(x); i++)
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}</lang>output<pre>-182 -175 -151 -141 -70 -51 -20 -5 -1 41 70 103 171 198 227 242</pre>
}</syntaxhighlight>output<pre>-182 -175 -151 -141 -70 -51 -20 -5 -1 41 70 103 171 198 227 242</pre>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
{{works with|C sharp|C#|3.0+}}
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace RadixSort
namespace RadixSort
Line 1,190: Line 1,190:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 1,196: Line 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.
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.
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>
#include <iterator>
#include <iterator>
Line 1,248: Line 1,248:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>-802 -90 2 24 45 66 75 170 </pre>
<pre>-802 -90 2 24 45 66 75 170 </pre>
Line 1,254: Line 1,254:
=={{header|D}}==
=={{header|D}}==
===Shorter Version===
===Shorter Version===
<lang d>import std.stdio, std.math, std.traits, std.range, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.math, std.traits, std.range, std.algorithm;


ElementType!R[] radixSort(size_t N=10, R)(R r)
ElementType!R[] radixSort(size_t N=10, R)(R r)
Line 1,286: Line 1,286:
items.radixSort().writeln();
items.radixSort().writeln();
items.map!q{1 - a}().radixSort().writeln();
items.map!q{1 - a}().radixSort().writeln();
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[-802, -90, 2, 24, 45, 66, 75, 170]
<pre>[-802, -90, 2, 24, 45, 66, 75, 170]
Line 1,292: Line 1,292:


===More Efficient Version===
===More Efficient Version===
<lang d>import std.array, std.traits;
<syntaxhighlight lang="d">import std.array, std.traits;


// considered pure for this program
// considered pure for this program
Line 1,349: Line 1,349:
items.radixSort();
items.radixSort();
writeln(items);
writeln(items);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[2, 24, 45, 66, 75, 170, 4294966494, 4294967206]</pre>
<pre>[2, 24, 45, 66, 75, 170, 4294966494, 4294967206]</pre>
Line 1,357: Line 1,357:
=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang># Radix sort - sorts positive integers
<syntaxhighlight lang="text"># Radix sort - sorts positive integers
#
#
func sort . data[] .
func sort . data[] .
Line 1,386: Line 1,386:
data[] = [ 29 4 72 44 55 26 27 77 92 5 ]
data[] = [ 29 4 72 44 55 26 27 77 92 5 ]
call sort data[]
call sort data[]
print data[]</lang>
print data[]</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
Works for positive integers. Splits up into two buckets according to the binary representation of the number.
Works for positive integers. Splits up into two buckets according to the binary representation of the number.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
RADIX_SORT
RADIX_SORT
Line 1,483: Line 1,483:


end
end
</syntaxhighlight>
</lang>
Test:
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,519: Line 1,519:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,530: Line 1,530:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule Sort do
<syntaxhighlight lang="elixir">defmodule Sort do
def radix_sort(list), do: radix_sort(list, 10)
def radix_sort(list), do: radix_sort(list, 10)
Line 1,553: Line 1,553:
end
end


IO.inspect Sort.radix_sort([-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028])</lang>
IO.inspect Sort.radix_sort([-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028])</syntaxhighlight>


{{out}}
{{out}}
Line 1,561: Line 1,561:


=={{header|Fortran}}==
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>


SUBROUTINE VARRADIX(A , Siz)
SUBROUTINE VARRADIX(A , Siz)
Line 2,017: Line 2,017:
END IF
END IF
END ! of test program
END ! of test program
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,028: Line 2,028:
=={{header|Go}}==
=={{header|Go}}==
LSD radix 256, negatives handled by flipping the high bit.
LSD radix 256, negatives handled by flipping the high bit.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,072: Line 2,072:
}
}
fmt.Println("sorted: ", data)
fmt.Println("sorted: ", data)
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,081: Line 2,081:
=={{header|Groovy}}==
=={{header|Groovy}}==
This solution assumes the radix is a power of 2:
This solution assumes the radix is a power of 2:
<lang groovy>def radixSort = { final radixExponent, list ->
<syntaxhighlight lang="groovy">def radixSort = { final radixExponent, list ->
def fromBuckets = new TreeMap([0:list])
def fromBuckets = new TreeMap([0:list])
def toBuckets = new TreeMap()
def toBuckets = new TreeMap()
Line 2,104: Line 2,104:
final twosComplIndx = [] + (keys.findAll(neg)) + (keys.findAll(pos))
final twosComplIndx = [] + (keys.findAll(neg)) + (keys.findAll(pos))
twosComplIndx.collect { fromBuckets[it] }.findAll { it != null }.flatten()
twosComplIndx.collect { fromBuckets[it] }.findAll { it != null }.flatten()
}</lang>
}</syntaxhighlight>


Test:
Test:
<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]))
<syntaxhighlight 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, [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]))
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 2,125: Line 2,125:
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, [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, [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]))</lang>
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]))</syntaxhighlight>


Output:
Output:
Line 2,151: Line 2,151:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>import Data.Bits (Bits(testBit, bitSize))
<syntaxhighlight lang="haskell">import Data.Bits (Bits(testBit, bitSize))
import Data.List (partition)
import Data.List (partition)


Line 2,172: Line 2,172:
aux (-1) list = list
aux (-1) list = list
aux bit list = aux (bit - 1) lower ++ aux (bit - 1) upper where
aux bit list = aux (bit - 1) lower ++ aux (bit - 1) upper where
(lower, upper) = partition (not . flip testBit bit) list</lang>
(lower, upper) = partition (not . flip testBit bit) list</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 2,179: Line 2,179:
contains a subtle inefficiency: subscripting a numeric value first coerces it into a string.
contains a subtle inefficiency: subscripting a numeric value first coerces it into a string.


<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
every writes((!rSort(A)||" ")|"\n")
every writes((!rSort(A)||" ")|"\n")
end
end
Line 2,192: Line 2,192:
}
}
return A
return A
end</lang>
end</syntaxhighlight>


Sample run:
Sample run:
Line 2,206: Line 2,206:
<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>.


<syntaxhighlight lang="j">
<lang j>
radixSortR =: 3 : 0 NB. base radixSort data
radixSortR =: 3 : 0 NB. base radixSort data
16 radixSortR y
16 radixSortR y
Line 2,217: Line 2,217:
end.
end.
x#.keys NB. restore the data
x#.keys NB. restore the data
)</lang>
)</syntaxhighlight>


An alternate implementation is
An alternate implementation is
<lang j>radixsort=: (] #~ [: +/ =/) i.@(>./)</lang>
<syntaxhighlight lang="j">radixsort=: (] #~ [: +/ =/) i.@(>./)</syntaxhighlight>


This uses the maximum value of the list for the base, which allows the list to be sorted in one pass.
This uses the maximum value of the list for the base, which allows the list to be sorted in one pass.
Line 2,226: Line 2,226:
Example use:
Example use:


<lang j> radixsort ?.@#~10
<syntaxhighlight lang="j"> radixsort ?.@#~10
4 5 6 6 6 6 6 8 8</lang>
4 5 6 6 6 6 6 8 8</syntaxhighlight>


Or, for negative number support:
Or, for negative number support:


<lang j>rsort=: (] + radixsort@:-) <./</lang>
<syntaxhighlight lang="j">rsort=: (] + radixsort@:-) <./</syntaxhighlight>


Example:
Example:


<lang j> rsort _6+?.@#~10
<syntaxhighlight lang="j"> rsort _6+?.@#~10
_2 _1 0 0 0 0 0 2 2</lang>
_2 _1 0 0 0 0 0 2 2</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>public static int[] sort(int[] old) {
<syntaxhighlight lang="java">public static int[] sort(int[] old) {
// Loop for every bit in the integers
// Loop for every bit in the integers
for (int shift = Integer.SIZE - 1; shift > -1; shift--) {
for (int shift = Integer.SIZE - 1; shift > -1; shift--) {
Line 2,272: Line 2,272:


return old;
return old;
}</lang>
}</syntaxhighlight>


{{trans|NetRexx}}
{{trans|NetRexx}}
<syntaxhighlight lang="java">
<lang Java>
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Arrays;
Line 2,394: Line 2,394:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,420: Line 2,420:


=={{header|jq}}==
=={{header|jq}}==
<lang jq># Sort the input array;
<syntaxhighlight lang="jq"># Sort the input array;
# "base" must be an integer greater than 1
# "base" must be an integer greater than 1
def radix_sort(base):
def radix_sort(base):
Line 2,443: Line 2,443:
def radix_sort:
def radix_sort:
radix_sort(10);
radix_sort(10);
</syntaxhighlight>
</lang>
'''Example'''
'''Example'''
<syntaxhighlight lang="jq">
<lang jq>
# Verify that radix_sort agrees with sort
# Verify that radix_sort agrees with sort
( [1, 3, 8, 9, 0, 0, 8, 7, 1, 6],
( [1, 3, 8, 9, 0, 0, 8, 7, 1, 6],
Line 2,451: Line 2,451:
[170, 45, 75, 90, 2, 24, -802, -66] )
[170, 45, 75, 90, 2, 24, -802, -66] )
| (radix_sort == sort)
| (radix_sort == sort)
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
true
true
Line 2,459: Line 2,459:
=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Scala}}
{{trans|Scala}}
<lang julia>function radixsort(tobesorted::Vector{Int64})
<syntaxhighlight lang="julia">function radixsort(tobesorted::Vector{Int64})
arr = deepcopy(tobesorted)
arr = deepcopy(tobesorted)
for shift in 63:-1:0
for shift in 63:-1:0
Line 2,486: Line 2,486:


testradixsort()
testradixsort()
</lang>{{output}}<pre>
</syntaxhighlight>{{output}}<pre>
[-802, -90, 2, 24, 45, 66, 75, 170]
[-802, -90, 2, 24, 45, 66, 75, 170]
[-1837, -990, -26, -4, 5, 58, 331, 331, 990, 2028]
[-1837, -990, -26, -4, 5, 58, 331, 331, 990, 2028]
Line 2,493: Line 2,493:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun radixSort(original: IntArray): IntArray {
fun radixSort(original: IntArray): IntArray {
Line 2,528: Line 2,528:
)
)
for (array in arrays) println(radixSort(array).contentToString())
for (array in arrays) println(radixSort(array).contentToString())
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,537: Line 2,537:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>ClearAll[SortByPos, RadixSort]
<syntaxhighlight lang="mathematica">ClearAll[SortByPos, RadixSort]
SortByPos[data : {_List ..}, pos_Integer] := Module[{digs, order},
SortByPos[data : {_List ..}, pos_Integer] := Module[{digs, order},
digs = data[[All, pos]];
digs = data[[All, pos]];
Line 2,553: Line 2,553:
digs += offset;
digs += offset;
digs
digs
]</lang>
]</syntaxhighlight>
Testing out the algorithm:
Testing out the algorithm:
<lang Mathematica>RadixSort[{170,45,75,-90,-802,24,2,66}]
<syntaxhighlight lang="mathematica">RadixSort[{170,45,75,-90,-802,24,2,66}]
RadixSort[{170,45,75,90,802,2,24,66}]</lang>
RadixSort[{170,45,75,90,802,2,24,66}]</syntaxhighlight>
{{out}}
{{out}}
<pre>{-802,-90,2,24,45,66,75,170}
<pre>{-802,-90,2,24,45,66,75,170}
Line 2,563: Line 2,563:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang Nim>func radixSort[T](a: openArray[T]): seq[T] =
<syntaxhighlight lang="nim">func radixSort[T](a: openArray[T]): seq[T] =


result = @a
result = @a
Line 2,595: Line 2,595:


for a in arrays:
for a in arrays:
echo radixSort(a)</lang>
echo radixSort(a)</syntaxhighlight>


{{out}}
{{out}}
Line 2,606: Line 2,606:
Limitations - Handles decimal digits only.
Limitations - Handles decimal digits only.
===Using the <tt>Rexx</tt> class===
===Using the <tt>Rexx</tt> class===
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,678: Line 2,678:
end il
end il
return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,709: Line 2,709:
</pre>
</pre>
===Using <tt>Collection</tt> classes===
===Using <tt>Collection</tt> classes===
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,795: Line 2,795:
end il
end il
return
return
</syntaxhighlight>
</lang>


=={{header|Perl}}==
=={{header|Perl}}==
Radix sort in base 10.
Radix sort in base 10.
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use warnings;
use strict;
use strict;
Line 2,831: Line 2,831:
$_ = 0 + $_ for @return; # Remove zeros.
$_ = 0 + $_ for @return; # Remove zeros.
return @return;
return @return;
}</lang>
}</syntaxhighlight>
To test, add the following lines:
To test, add the following lines:
<lang perl>use Test::More tests => 1000;
<syntaxhighlight lang="perl">use Test::More tests => 1000;


for (1 .. 1000) {
for (1 .. 1000) {
my @l = map int rand(2000) - 1000, 0 .. 20;
my @l = map int rand(2000) - 1000, 0 .. 20;
is_deeply([radix(@l)], [sort { $a <=> $b } @l]);
is_deeply([radix(@l)], [sort { $a <=> $b } @l]);
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,895: Line 2,895:
<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;">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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,906: Line 2,906:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
This is a LSD base-2 radix sort using queues:
This is a LSD base-2 radix sort using queues:
<lang PicoLisp>(de radixSort (Lst)
<syntaxhighlight lang="picolisp">(de radixSort (Lst)
(let Mask 1
(let Mask 1
(while
(while
Line 2,920: Line 2,920:
Mask (* 2 Mask) )
Mask (* 2 Mask) )
Flg ) ) )
Flg ) ) )
Lst )</lang>
Lst )</syntaxhighlight>
Output:
Output:
<pre>: (radixSort (make (do 12 (link (rand -999 999)))))
<pre>: (radixSort (make (do 12 (link (rand -999 999)))))
Line 2,926: Line 2,926:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Structure bucket
<syntaxhighlight lang="purebasic">Structure bucket
List i.i()
List i.i()
EndStructure
EndStructure
Line 3,011: Line 3,011:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>0, 0, 1, 1, 3, 6, 7, 8, 8, 9
<pre>0, 0, 1, 1, 3, 6, 7, 8, 8, 9
Line 3,022: Line 3,022:
This is the Wikipedia example code extended with an extra pass to sort negative values correctly.
This is the Wikipedia example code extended with an extra pass to sort negative values correctly.


<lang python>#python2.6 <
<syntaxhighlight lang="python">#python2.6 <
from math import log
from math import log
Line 3,069: Line 3,069:
new_list = merge(split(new_list, base, digit_num))
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list))
return merge(split_by_sign(new_list))
</syntaxhighlight>
</lang>


An alternate implementation using which works on Python 3:
An alternate implementation using which works on Python 3:


<lang python>#python3.7 <
<syntaxhighlight lang="python">#python3.7 <
def flatten(some_list):
def flatten(some_list):
"""
"""
Line 3,146: Line 3,146:


return flattened_result
return flattened_result
</syntaxhighlight>
</lang>


That same example but more compact:
That same example but more compact:


<lang python>#python3.7 <
<syntaxhighlight lang="python">#python3.7 <
def flatten(l):
def flatten(l):
return [y for x in l for y in x]
return [y for x in l for y in x]
Line 3,171: Line 3,171:


return flatten([radix(b, p-1, s) for b in bins])
return flatten([radix(b, p-1, s) for b in bins])
</syntaxhighlight>
</lang>


=={{header|QB64}}==
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>
#lang QB64
#lang QB64
'* don't be an a$$. Keep this credit notice with the source:
'* don't be an a$$. Keep this credit notice with the source:
Line 3,479: Line 3,479:
END SELECT
END SELECT
END SUB
END SUB
</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ stack ] is digit ( --> s )
<syntaxhighlight lang="quackery"> [ stack ] is digit ( --> s )


[ behead swap witheach min ] is smallest ( [ --> n )
[ behead swap witheach min ] is smallest ( [ --> n )
Line 3,528: Line 3,528:
100 < if sp
100 < if sp
echo sp ] cr ]
echo sp ] cr ]
drop</lang>
drop</syntaxhighlight>


{{out}}
{{out}}
Line 3,551: Line 3,551:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang Racket
#lang Racket
(define (radix-sort l r)
(define (radix-sort l r)
Line 3,577: Line 3,577:
(sorted? (radix-sort (make-random-list) (+ 2 (random 98)))))
(sorted? (radix-sort (make-random-list) (+ 2 (random 98)))))
;; => #t, so all passed
;; => #t, so all passed
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(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.)
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) {
<syntaxhighlight lang="raku" line>sub radsort (@ints) {
my $maxlen = max @ints».chars;
my $maxlen = max @ints».chars;
my @list = @ints».fmt("\%0{$maxlen}d");
my @list = @ints».fmt("\%0{$maxlen}d");
Line 3,595: Line 3,595:
}
}


.say for radsort (-2_000 .. 2_000).roll(20);</lang>
.say for radsort (-2_000 .. 2_000).roll(20);</syntaxhighlight>
{{out}}
{{out}}
<pre>-1585
<pre>-1585
Line 3,620: Line 3,620:
=={{header|REXX}}==
=={{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.
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.
<lang rexx>/*REXX program performs a radix sort on an integer array (can be negative/zero/positive)*/
<syntaxhighlight 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 gen /*call subroutine to generate numbers. */
call radSort n, w /*invoke the radix sort subroutine. */
call radSort n, w /*invoke the radix sort subroutine. */
Line 3,685: Line 3,685:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do j=1 for n; say 'item' right(j, w) "after the radix sort:" right(@.j, w)
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.*/</lang>
end /*j*/; return /* [↑] display sorted items ───► term.*/</syntaxhighlight>
{{out|output|text=&nbsp; &nbsp; (with the middle section elided.)}}
{{out|output|text=&nbsp; &nbsp; (with the middle section elided.)}}


Line 3,737: Line 3,737:
=={{header|Ruby}}==
=={{header|Ruby}}==
Negative number handling courtesy the Tcl solution.
Negative number handling courtesy the Tcl solution.
<lang ruby>class Array
<syntaxhighlight lang="ruby">class Array
def radix_sort(base=10)
def radix_sort(base=10)
ary = dup
ary = dup
Line 3,762: Line 3,762:
p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort
p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort
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</lang>
p [100000, -10000, 400, 23, 10000].radix_sort</syntaxhighlight>
running with $DEBUG on produces:
running with $DEBUG on produces:
<pre>[0, [0, 0, 1, 1, 3, 6, 7, 8, 8, 9]]
<pre>[0, [0, 0, 1, 1, 3, 6, 7, 8, 8, 9]]
Line 3,783: Line 3,783:


another version (After sorting at the absolute value, it makes a negative order reverse.)
another version (After sorting at the absolute value, it makes a negative order reverse.)
<lang ruby>class Array
<syntaxhighlight lang="ruby">class Array
def radix_sort(base=10)
def radix_sort(base=10)
ary = dup
ary = dup
Line 3,795: Line 3,795:
ary.partition{|n| n<0}.inject{|minus,plus| minus.reverse + plus}
ary.partition{|n| n<0}.inject{|minus,plus| minus.reverse + plus}
end
end
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) {
fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) {
let (left, right) = out.split_at_mut(in1.len());
let (left, right) = out.split_at_mut(in1.len());
Line 3,824: Line 3,824:
println!("After: {:?}", data);
println!("After: {:?}", data);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,832: Line 3,832:


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>object RadixSort extends App {
<syntaxhighlight lang="scala">object RadixSort extends App {
def sort(toBeSort: Array[Int]): Array[Int] = { // Loop for every bit in the integers
def sort(toBeSort: Array[Int]): Array[Int] = { // Loop for every bit in the integers
var arr = toBeSort
var arr = toBeSort
Line 3,857: Line 3,857:


println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", "))
println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", "))
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 3,865: Line 3,865:




<lang Scheme>;;; An illustrative implementation of the radix-10 example at
<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
;;; https://en.wikipedia.org/w/index.php?title=Radix_sort&oldid=1070890278#Least_significant_digit


Line 3,911: Line 3,911:
(radix-sort data)
(radix-sort data)
(write data)
(write data)
(newline)</lang>
(newline)</syntaxhighlight>


{{out}}
{{out}}
Line 3,924: Line 3,924:
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.
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.


<lang Scheme>;;; An illustrative implementation of the radix-10 example at
<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
;;; https://en.wikipedia.org/w/index.php?title=Radix_sort&oldid=1070890278#Least_significant_digit


Line 3,995: Line 3,995:
(radix-sort data)
(radix-sort data)
(write data)
(write data)
(newline)</lang>
(newline)</syntaxhighlight>


{{out}}
{{out}}
Line 4,007: Line 4,007:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>class Array {
<syntaxhighlight lang="ruby">class Array {
method radix_sort(base=10) {
method radix_sort(base=10) {
var arr = self.clone
var arr = self.clone
Line 4,032: Line 4,032:
] {
] {
say arr.radix_sort
say arr.radix_sort
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,042: Line 4,042:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
templates radixsort&{base:}
templates radixsort&{base:}
sink bucketize
sink bucketize
Line 4,080: Line 4,080:
' -> !OUT::write
' -> !OUT::write
[170, 45, 75, -91, -90, -92, -802, 24, 2, 66] -> radixsort&{base:3} -> !OUT::write
[170, 45, 75, -91, -90, -92, -802, 24, 2, 66] -> radixsort&{base:3} -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,091: Line 4,091:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{trans|Python}}
{{trans|Python}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
proc splitByRadix {lst base power} {
proc splitByRadix {lst base power} {
# create a list of empty lists to hold the split by digit
# create a list of empty lists to hold the split by digit
Line 4,123: Line 4,123:
}
}
return $lst
return $lst
}</lang>
}</syntaxhighlight>
Demonstrations:
Demonstrations:
<lang tcl>puts [radixSort {1 3 8 9 0 0 8 7 1 6}]
<syntaxhighlight 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}]
puts [radixSort {170 45 75 90 2 24 -802 -66}]</lang>
puts [radixSort {170 45 75 90 2 24 -802 -66}]</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 4,137: Line 4,137:
=={{header|Wren}}==
=={{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.
This is based on the approach used [https://www.geeksforgeeks.org/radix-sort/ here] which I've adjusted to deal with negative elements.
<lang ecmascript>// counting sort of 'a' according to the digit represented by 'exp'
<syntaxhighlight lang="ecmascript">// counting sort of 'a' according to the digit represented by 'exp'
var countSort = Fn.new { |a, exp|
var countSort = Fn.new { |a, exp|
var n = a.count
var n = a.count
Line 4,178: Line 4,178:
radixSort.call(a)
radixSort.call(a)
System.print("Sorted : %(a)\n")
System.print("Sorted : %(a)\n")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,191: Line 4,191:
=={{header|zkl}}==
=={{header|zkl}}==
In place int sort, fairly light on garbage creation.
In place int sort, fairly light on garbage creation.
<lang zkl>fcn radixSort(ns){ // ints only, inplace, ns is mutable
<syntaxhighlight lang="zkl">fcn radixSort(ns){ // ints only, inplace, ns is mutable
b:=(0).pump(20,List,List().copy); // 20 [empty] buckets: -10..10
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|
z:=ns.reduce(fcn(a,b){ a.abs().max(b.abs()) },0); // |max or min of input|
Line 4,202: Line 4,202:
}
}
ns
ns
}</lang>
}</syntaxhighlight>
<lang zkl>radixSort(T(170, 45, 75, 90, 802, 2, 24, 66)).println();
<syntaxhighlight lang="zkl">radixSort(T(170, 45, 75, 90, 802, 2, 24, 66)).println();
radixSort(T(170, 45, 75, -90, -802, 24, 2, 66)).println();</lang>
radixSort(T(170, 45, 75, -90, -802, 24, 2, 66)).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>