Sorting algorithms/Bead sort: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(40 intermediate revisions by 23 users not shown)
Line 1:
{{task|Sorting Algorithms}}{{Sorting Algorithm}}
[[Category:Sorting]]
 
{{Sorting Algorithm}}
 
;Task:
Sort an array of positive integers using the [[wp:Bead_sort|Bead Sort Algorithm]].
 
A   ''bead sort''   is also known as a   ''gravity sort''.
 
 
Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually.
 
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F bead_sort(&a)
V maxv = max(a)
V beads = [0] * (maxv * a.len)
 
L(i) 0 .< a.len
L(j) 0 .< a[i]
beads[i * maxv + j] = 1
 
L(j) 0 .< maxv
V sum = 0
L(i) 0 .< a.len
sum += beads[i * maxv + j]
beads[i * maxv + j] = 0
 
L(i) a.len - sum .< a.len
beads[i * maxv + j] = 1
 
L(i) 0 .< a.len
V j = 0
L j < maxv & beads[i * maxv + j] > 0
j++
a[i] = j
 
V a = [5, 3, 1, 7, 4, 1, 1, 20]
bead_sort(&a)
print(a)</syntaxhighlight>
 
{{out}}
<pre>
[1, 1, 1, 3, 4, 5, 7, 20]
</pre>
 
=={{header|360 Assembly}}==
Line 15 ⟶ 53:
For maximum compatibility, this program uses only the basic instruction set (S/360)
and two ASSIST macros (XDECO,XPRNT) to keep it as short as possible.
<langsyntaxhighlight lang="360asm">* Bead Sort 11/05/2016
BEADSORT CSECT
USING BEADSORT,R13 base register
Line 113 ⟶ 151:
BEADS DC 4096X'00' beads
YREGS
END BEADSORT</langsyntaxhighlight>
{{out}}
<pre>
Line 119 ⟶ 157:
sorted: -2010 -12 -1 0 1 3 4 5 7 9 17 2001
</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 beadSort64.s */
/* En français tri par gravité ou tri par bille (ne pas confondre
avec tri par bulle (bubble sort)) */
/*******************************************/
/* 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 1,3,6,2,5,9,10,8,4,7
TableNumber: .quad 10,9,8,7,6,5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
//.equ NBELEMENTS, 4 // for others tests
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
1:
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl beadSort
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,#1 // sorted ?
beq 2f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
2: // 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
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] // load A[0]
1:
add x2,x2,#1
cmp x2,x1 // end ?
bge 99f
ldr x3,[x0,x2, lsl #3] // load A[i]
cmp x3,x4 // compare A[i],A[i-1]
blt 98f // smaller -> error -> return
mov x4,x3 // no -> A[i-1] = A[i]
b 1b // and loop
98:
mov x0,#0 // error
b 100f
99:
mov x0,#1 // ok -> return
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* bead sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of element */
/* Caution registers x2-x12 are not saved */
beadSort:
stp x1,lr,[sp,-16]! // save registers
mov x12,x1 // save elements number
//search max
ldr x10,[x0] // load value A[0] in max
mov x4,#1
1: // loop search max
cmp x4,x12 // end ?
bge 21f // yes
ldr x2,[x0,x4,lsl #3] // load value A[i]
cmp x2,x10 // compare with max
csel x10,x2,x10,gt // if greather
add x4,x4,#1
b 1b // loop
21:
mul x5,x10,x12 // max * elements number
lsl x5,x5,#3 // 8 bytes for each number
sub sp,sp,x5 // allocate on the stack
mov fp,sp // frame pointer = stack address
// marks beads
mov x3,x0 // save table address
mov x0,#0 // start index x
2:
mov x1,#0 // index y
ldr x8,[x3,x0,lsl #3] // load A[x]
mul x6,x0,x10 // compute bead x
3:
add x9,x6,x1 // compute bead y
mov x4,#1 // value to store
str x4,[fp,x9,lsl #3] // store to stack area
add x1,x1,#1
cmp x1,x8
blt 3b
31: // init to zéro the bead end
cmp x1,x10 // max ?
bge 32f
add x9,x6,x1 // compute bead y
mov x4,#0
str x4,[fp,x9,lsl #3]
add x1,x1,#1
b 31b
32:
add x0,x0,#1 // increment x
cmp x0,x12 // end ?
blt 2b
// count beads
mov x1,#0 // y
4:
mov x0,#0 // start index x
mov x8,#0 // sum
5:
mul x6,x0,x10 // compute bead x
add x9,x6,x1 // compute bead y
ldr x4,[fp,x9,lsl #3]
add x8,x8,x4
mov x4,#0
str x4,[fp,x9,lsl #3] // raz bead
add x0,x0,#1
cmp x0,x12
blt 5b
sub x0,x12,x8 // compute end - sum
6:
mul x6,x0,x10 // compute bead x
add x9,x6,x1 // compute bead y
mov x4,#1
str x4,[fp,x9,lsl #3] // store new bead at end
add x0,x0,#1
cmp x0,x12
blt 6b
add x1,x1,#1
cmp x1,x10
blt 4b
// final compute
mov x0,#0 // start index x
7:
mov x1,#0 // start index y
mul x6,x0,x10 // compute bead x
8:
add x9,x6,x1 // compute bead y
ldr x4,[fp,x9,lsl #3] // load bead [x,y]
add x1,x1,#1 // add to x1 before str (index start at zéro)
cmp x4,#1
bne 9f
str x1,[x3,x0, lsl #3] // store A[x]
9:
cmp x1,x10 // compare max
blt 8b
add x0,x0,#1
cmp x0,x12 // end ?
blt 7b
 
mov x0,#0
add sp,sp,x5 // stack alignement
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains elements number */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x4,x1 // elements number
mov x3,#0
1: // loop display table
ldr x0,[x2,x3,lsl #3]
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
bl affichageMess // display message
add x3,x3,#1
cmp x3,x4 // end ?
blt 1b // no -> loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
 
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
 
</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program beadSort.s */
/* En français tri par gravité ou tri par bille (ne pas confondre
avec tri par bulle (bubble sort) */
/* 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,3,6,2,5,9,10,8,4,7
#TableNumber: .int 10,9,8,7,6,5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 4
@.equ NBELEMENTS, 4 @ for others tests
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl beadSort
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 2f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
2: @ 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] @ load A[0]
1:
add r2,#1
cmp r2,r1 @ end ?
movge r0,#1 @ yes -> ok -> return
bge 100f
ldr r3,[r0,r2, lsl #2] @ load A[i]
cmp r3,r4 @ compare A[i],A[i-1]
movlt r0,#0 @ smaller ?
blt 100f @ yes -> error -> return
mov r4,r3 @ no -> A[i-1] = A[i]
b 1b @ and loop
100:
pop {r2-r4,lr}
bx lr @ return
/******************************************************************/
/* bead sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of element */
beadSort:
push {r1-r12,lr} @ save registers
mov r12,r1 @ save elements number
@search max
ldr r10,[r0] @ load value A[0] in max
mov r4,#1
1: @ loop search max
cmp r4,r12 @ end ?
bge 21f @ yes
ldr r2,[r0,r4,lsl #2] @ load value A[i]
cmp r2,r10 @ compare with max
movgt r10,r2 @ if greather
add r4,r4,#1
b 1b @ loop
21:
mul r5,r10,r12 @ max * elements number
lsl r5,r5,#2 @ 4 bytes for each number
sub sp,sp,r5 @ allocate on the stack
mov fp,sp @ frame pointer = stack address
@ marks beads
mov r3,r0 @ save table address
mov r0,#0 @ start index x
2:
mov r1,#0 @ index y
ldr r7,[r3,r0,lsl #2] @ load A[x]
mul r6,r0,r10 @ compute bead x
3:
add r9,r6,r1 @ compute bead y
mov r4,#1 @ value to store
str r4,[fp,r9,lsl #2] @ store to stack area
add r1,r1,#1
cmp r1,r7
blt 3b
31: @ init to zéro the bead end
cmp r1,r10 @ max ?
bge 32f
add r9,r6,r1 @ compute bead y
mov r4,#0
str r4,[fp,r9,lsl #2]
add r1,r1,#1
b 31b
32:
add r0,r0,#1 @ increment x
cmp r0,r12 @ end ?
blt 2b
@ count beads
mov r1,#0 @ y
4:
mov r0,#0 @ start index x
mov r8,#0 @ sum
5:
mul r6,r0,r10 @ compute bead x
add r9,r6,r1 @ compute bead y
ldr r4,[fp,r9,lsl #2]
add r8,r8,r4
mov r4,#0
str r4,[fp,r9,lsl #2]
add r0,r0,#1
cmp r0,r12
blt 5b
sub r0,r12,r8
6:
mul r6,r0,r10 @ compute bead x
add r9,r6,r1 @ compute bead y
mov r4,#1
str r4,[fp,r9,lsl #2]
add r0,r0,#1
cmp r0,r12
blt 6b
add r1,r1,#1
cmp r1,r10
blt 4b
@ suite
mov r0,#0 @ start index
7:
mov r1,#0
mul r6,r0,r10 @ compute bead x
8:
add r9,r6,r1 @ compute bead y
ldr r4,[fp,r9,lsl #2]
add r1,r1,#1 @ add to r1 before str (index start at zéro)
cmp r4,#1
streq r1,[r3,r0, lsl #2] @ store A[i]
cmp r1,r10 @ compare max
blt 8b
add r0,r0,#1
cmp r0,r12 @ end ?
blt 7b
 
mov r0,#0
add sp,sp,r5 @ stack alignement
100:
pop {r1-r12,lr}
bx lr @ return
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains elements number */
displayTable:
push {r0-r4,lr} @ save registers
mov r2,r0 @ table address
mov r4,r1 @ elements number
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsZoneConv
bl conversion10 @ décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,r3,#1
cmp r3,r4 @ end ?
blt 1b @ no -> loop
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r4,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
 
</syntaxhighlight>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">beadSort: function [items][
a: new items
m: neg infinity
s: 0
 
loop a 'x [
if x > m -> m: x
]
 
beads: array.of: m * size a 0
 
loop 0..dec size a 'i [
loop 0..dec a\[i] 'j ->
beads\[j + i * m]: 1
]
 
loop 0..dec m 'j [
s: 0
loop 0..dec size a 'i [
s: s + beads\[j + i*m]
beads\[j + i*m]: 0
]
 
loop ((size a)-s)..dec size a 'i ->
beads\[j + i*m]: 1
]
 
loop 0..dec size a 'i [
j: 0
while [and? [j < m] [beads\[j + i*m] > 0]] -> j: j + 1
a\[i]: j
]
 
return a
]
 
print beadSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">BeadSort(data){
Pole:=[] , TempObj:=[], Result:=[]
for, i, v in data {
Line 144 ⟶ 697:
}
return Result
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">for i, val in BeadSort([54,12,87,56,36])
res := val (res?",":"") res
MsgBox % res</langsyntaxhighlight>
{{out}}
<pre>12,36,54,56,87</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let max(A, len) = valof
$( let x = 0
for i=0 to len-1
if x<A!i do x := A!i
resultis x
$)
 
let beadsort(A, len) be
$( let size = max(A, len)
let tvec = getvec(size-1)
for i=0 to size-1 do tvec!i := 0
for i=0 to len-1
for j=0 to A!i-1 do tvec!j := tvec!j + 1
for i=len-1 to 0 by -1
$( let n = 0
for j=0 to size-1
if tvec!j > 0
$( tvec!j := tvec!j - 1
n := n + 1
$)
A!i := n
$)
freevec(tvec)
$)
 
let write(s, A, len) be
$( writes(s)
for i=0 to len-1 do writed(A!i, 4)
wrch('*N')
$)
let start() be
$( let array = table 10,1,5,5,9,2,20,6,8,4
let length = 10
write("Before: ", array, length)
beadsort(array, length)
write("After: ", array, length)
$)</syntaxhighlight>
{{out}}
<pre>Before: 10 1 5 5 9 2 20 6 8 4
After: 1 2 4 5 5 6 8 9 10 20</pre>
 
=={{header|C}}==
Line 155 ⟶ 753:
Requires (max * length) bytes for beads; if memory is of concern, bytes can be replaced by bits.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 201 ⟶ 799:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">//this algorithm only works with positive, whole numbers.
//O(2n) time complexity where n is the summation of the whole list to be sorted.
//O(3n) space complexity.
Line 252 ⟶ 850:
for(unsigned int i=0; i<sorted.size(); i++)
cout << sorted[i] << ' ';
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
{{trans|Haskell}}
<langsyntaxhighlight Clojurelang="clojure">(defn transpose [xs]
(loop [ret [], remain xs]
(if (empty? remain)
Line 265 ⟶ 863:
(defn bead-sort [xs]
(->> xs
(map #(repeat 1 % 1))
transpose
transpose
(map #(reduce + %))))
;; This algorithm does not work if collection has zero
(-> [5 2 4 1 3 3 9] bead-sort println)
</syntaxhighlight>
</lang>
 
{{out}}
Line 278 ⟶ 877:
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<langsyntaxhighlight COBOLlang="cobol"> >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCOBOL 2.0
Line 375 ⟶ 974:
end-perform
.
end program beadsort.</langsyntaxhighlight>
 
{{out}}
Line 408 ⟶ 1,007:
=={{header|Common Lisp}}==
{{trans|Clojure}}
<langsyntaxhighlight lang="lisp">
(defun transpose (remain &optional (ret '()))
(if (null remain)
Line 419 ⟶ 1,018:
 
(bead-sort '(5 2 4 1 3 3 9))
</syntaxhighlight>
</lang>
{{out}}
<pre>(9 5 4 3 3 2 1)</pre>
 
=={{header|D}}==
A functional-style solution.
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.array, std.functional;
 
alias repeat0 = curry!(repeat, 0);
 
// Currenty std.range.transposed doesn't work.
auto columns(R)(R m) pure /*nothrow*/ @safe /*@nogc*/ {
return m
.map!walkLength
.reduce!max
.iota
.map!(i => m.filter!(s => s.length > i).walkLength.repeat0);
}
 
auto beadSort(in uint[] data) pure /*nothrow @nogc*/ {
return data.map!repeat0.columns.columns.map!walkLength;
}
 
void main() {
[5, 3, 1, 7, 4, 1, 1].beadSort.writeln;
}</syntaxhighlight>
{{out}}
<pre>[7, 5, 4, 3, 1, 1, 1]</pre>
 
=={{header|Delphi}}==
{{trans|C}}
<langsyntaxhighlight lang="d">program BeadSortTest;
 
{$APPTYPE CONSOLE}
Line 490 ⟶ 1,114:
 
readln;
end.</langsyntaxhighlight>
--[[User:Davidizadar|DavidIzadaR]] 18:12, 7 August 2011 (UTC)
 
=={{header|D}}==
A functional-style solution.
<lang d>import std.stdio, std.algorithm, std.range, std.array, std.functional;
 
alias repeat0 = curry!(repeat, 0);
 
// Currenty std.range.transposed doesn't work.
auto columns(R)(R m) pure /*nothrow*/ @safe /*@nogc*/ {
return m
.map!walkLength
.reduce!max
.iota
.map!(i => m.filter!(s => s.length > i).walkLength.repeat0);
}
 
auto beadSort(in uint[] data) pure /*nothrow @nogc*/ {
return data.map!repeat0.columns.columns.map!walkLength;
}
 
void main() {
[5, 3, 1, 7, 4, 1, 1].beadSort.writeln;
}</lang>
{{out}}
<pre>[7, 5, 4, 3, 1, 1, 1]</pre>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
BEAD_SORT
Line 603 ⟶ 1,202:
 
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 640 ⟶ 1,239:
end
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 651 ⟶ 1,250:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Sort do
def bead_sort(list) when is_list(list), do: dist(dist(list))
Line 660 ⟶ 1,259:
defp dist([], n, acc), do: dist([], n-1, [1 |acc])
defp dist([h|t], n, acc), do: dist(t, n-1, [h+1|acc])
end</langsyntaxhighlight>
 
Example:
Line 669 ⟶ 1,268:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(beadsort).
 
-export([sort/1]).
Line 686 ⟶ 1,285:
dist(T, 0, [H | Acc]);
dist([], 0, Acc) ->
lists:reverse(Acc).</langsyntaxhighlight>
Example;
<langsyntaxhighlight lang="erlang">1> beadsort:sort([1,734,24,3,324,324,32,432,42,3,4,1,1]).
[734,432,324,324,42,32,24,4,3,3,1,1,1]</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="fsharp">open System
 
let removeEmptyLists lists = lists |> List.filter (not << List.isEmpty)
Line 706 ⟶ 1,305:
 
// Using the forward composition operator ">>" ...
let beadSort2 = List.map (flip List.replicate 1) >> transpose >> transpose >> List.map List.sum</langsyntaxhighlight>
Usage: beadSort [2;4;1;3;3] or beadSort2 [2;4;1;3;3]
 
Line 715 ⟶ 1,314:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: kernel math math.order math.vectors sequences ;
: fill ( seq len -- newseq ) [ dup length ] dip swap - 0 <repetition> append ;
 
Line 723 ⟶ 1,322:
[ ] [ v+ ] map-reduce ;
 
: beadsort ( seq -- newseq ) bead bead ;</langsyntaxhighlight>
<langsyntaxhighlight lang="factor">( scratchpad ) { 5 2 4 1 3 3 9 } beadsort .
{ 9 5 4 3 3 2 1 }</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 738 ⟶ 1,337:
very same code would run fine even with large integers.
 
<langsyntaxhighlight lang="fortran">program BeadSortTest
use iso_fortran_env
! for ERROR_UNIT; to make this a F95 code,
Line 778 ⟶ 1,377:
end subroutine beadsort
 
end program BeadSortTest</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#define MAXNUM 100
 
Sub beadSort(bs() As Long)
Dim As Long i, j = 1, lb = Lbound(bs), ub = Ubound(bs)
Dim As Long poles(MAXNUM)
For i = 1 To ub
For j = 1 To bs(i)
poles(j) += 1
Next j
Next i
For j = 1 To ub
bs(j) = 0
Next j
For i = 1 To Ubound(poles)
For j = 1 To poles(i)
bs(j) += 1
Next j
Next i
End Sub
 
'--- Programa Principal ---
Dim As Long i
Dim As Ulong array(1 To 8) => {5, 3, 1, 7, 4, 1, 1, 20}
Dim As Long a = Lbound(array), b = Ubound(array)
 
Randomize Timer
 
Print "unsort ";
For i = a To b : Print Using "####"; array(i); : Next i
 
beadSort(array())
 
Print !"\n sort ";
For i = a To b : Print Using "####"; array(i); : Next i
 
Print !"\n--- terminado, pulsa RETURN---"
Sleep</syntaxhighlight>
{{out}}
<pre>unsort 5 3 1 7 4 1 1 20
sort 20 7 5 4 3 1 1 1</pre>
 
=={{header|Go}}==
Sorts non-negative integers only. The extension to negative values seemed a distraction from this fun task.
<langsyntaxhighlight lang="go">package main
 
import (
Line 855 ⟶ 1,498:
a[len(a)-1-row] = x
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def beadSort = { list ->
final nPoles = list.max()
list.collect {
Line 870 ⟶ 1,513:
beadTally.findAll{ it }.size()
}
}</langsyntaxhighlight>
 
Annotated Solution (same solution really):
<langsyntaxhighlight lang="groovy">def beadSortVerbose = { list ->
final nPoles = list.max()
// each row is a number tally-arrayed across the abacus
Line 891 ⟶ 1,534:
def beadTalliesDrop = abacusPolesDrop.transpose()
beadTalliesDrop.collect{ beadTally -> beadTally.findAll{ it }.size() }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println beadSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])
println beadSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])</langsyntaxhighlight>
 
{{out}}
Line 906 ⟶ 1,549:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
 
beadSort :: [Int] -> [Int]
beadSort = map sum. transpose. transpose. map (flip replicate 1)</langsyntaxhighlight>
Example;
<langsyntaxhighlight lang="haskell">*Main> beadSort [2,4,1,3,3]
[4,3,3,2,1]</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The program below handles integers and not just whole numbers. As are so many others, the solution is limited by the lack of sparse array or list compression.
 
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
write("Sorting Demo using ",image(beadsort))
writes(" on list : ")
Line 941 ⟶ 1,584:
}
return X
end</langsyntaxhighlight>
 
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'writex' in Bubble Sort]].
Line 955 ⟶ 1,598:
{{eff note|J|\:~}}
 
<langsyntaxhighlight lang="j">bead=: [: +/ #"0&1</langsyntaxhighlight>
 
Example use:
 
<syntaxhighlight lang="text"> bead bead 2 4 1 3 3
4 3 3 2 1
bead bead 5 3 1 7 4 1 1
7 5 4 3 1 1 1</langsyntaxhighlight>
 
Extending to deal with sequences of arbitrary integers:
 
<langsyntaxhighlight lang="j">bball=: ] (] + [: bead^:2 -) <./ - 1:</langsyntaxhighlight>
 
Example use:
 
<syntaxhighlight lang="text"> bball 2 0 _1 3 1 _2 _3 0
3 2 1 0 0 _1 _2 _3</langsyntaxhighlight>
 
=={{header|Java}}==
 
<syntaxhighlight lang="java">
<lang Java>
 
public class BeadSort
Line 994 ⟶ 1,637:
int[] beadSort(int[] arr)
{
int max=a[0];
for(int i=01;i<arr.length;i++)
if(arr[i]>max)
max=arr[i];
Line 1,057 ⟶ 1,700:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,089 ⟶ 1,732:
 
'''Part 2: Gravity'''
<langsyntaxhighlight lang="jq"># ncols is the number of columns (i.e. vertical poles)
def column_sums(ncols):
. as $abacus
Line 1,095 ⟶ 1,738:
([];
. + [reduce $abacus[] as $row
(0; if $row > $col then .+1 else . end)]) ;</langsyntaxhighlight>
'''Part 3: read the answer in order of largest-to-smallest'''
<langsyntaxhighlight lang="jq"># Generic function to count the number of items in a stream:
def count(stream): reduce stream as $i (0; .+1);
 
Line 1,104 ⟶ 1,747:
| .[0] as $n
| reduce range(0;$n) as $i
([]; . + [count( $sums[] | select( . > $i) )]);</langsyntaxhighlight>
'''"Bead Sort":'''
<langsyntaxhighlight lang="jq">def bead_sort: column_sums(max) | readout;</langsyntaxhighlight>
 
'''Example:'''
<langsyntaxhighlight lang="jq">[734,3,1,24,324,324,32,432,42,3,4,1,1] | bead_sort</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -c -f bead_sort.jq
[734,432,324,324,42,32,24,4,3,3,1,1,1]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Implement <code>beadsort</code> on a <code>BitArray</code> ''abacus''. The function should work for any integer type. It throws a <code>DomainError</code> if the input array contains a non-positive integer.
<syntaxhighlight lang="julia">function beadsort(a::Vector{<:Integer})
<lang Julia>
lo, hi = extrema(a)
function beadsort{T<:Integer}(a::Array{T,1})
(if lo, hi)< =1 extremathrow(DomainError(a)) end
if lo < 1
throw(DomainError())
end
hi = convert(Int, hi)
len = length(a)
abacus = falses(len, hi)
for (i, v) in enumerate(a)
abacus[i, 1:v] = true
end
for i in 1:hi
v = sum(abacus[:, i])
if v < len
abacus[1:end-v, i] = false
abacus[end-v+1:end, i] = true
end
end
return T[collect(eltype(a), sum(abacus[i,:]) for i in 1:len])
end
 
av = Uint8[rand(1:typemax(Uint8))UInt8, for i in 1:20])
println("Sort# ofunsorted Unsignedbytes: Bytes$v\n -> sorted bytes: $(beadsort(v))")
v = rand(1:2 ^ 10, 20)
println(" Before Sort:")
println("# unsorted integers: $v\n -> sorted integers: $(beadsort(v))")</syntaxhighlight>
println(" ", a)
a = beadsort(a)
println("\n After Sort:")
println(" ", a, "\n")
 
a = [rand(1:2^10) for i in 1:20]
println("Sort of Integers:")
println(" Before Sort:")
println(" ", a)
a = beadsort(a)
println("\n After Sort:")
println(" ", a)
</lang>
 
{{out}}
<pre># unsorted bytes: UInt8[0xff, 0x52, 0xdd, 0x72, 0xe2, 0x13, 0xb5, 0xd3, 0x7f, 0xea, 0x3b, 0x46, 0x4b, 0x78, 0xfb, 0xbe, 0xd8, 0x2e, 0xa9, 0x7a]
<pre>
-> sorted bytes: UInt8[0x13, 0x2e, 0x3b, 0x46, 0x4b, 0x52, 0x72, 0x78, 0x7a, 0x7f, 0xa9, 0xb5, 0xbe, 0xd3, 0xd8, 0xdd, 0xe2, 0xea, 0xfb, 0xff]
Sort of Unsigned Bytes:
# unsorted integers: [1012, 861, 798, 949, 481, 889, 78, 699, 718, 195, 426, 922, 762, 360, 1017, 208, 304, 13, 910, 854]
Before Sort:
-> sorted integers: [13, 78, 195, 208, 304, 360, 426, 481, 699, 718, 762, 798, 854, 861, 889, 910, 922, 949, 1012, 1017]</pre>
Uint8[134,68,81,149,71,92,113,179,123,211,214,207,16,218,27,171,25,30,140,236]
 
=={{header|Kotlin}}==
After Sort:
{{trans|C}}
Uint8[16,25,27,30,68,71,81,92,113,123,134,140,149,171,179,207,211,214,218,236]
<syntaxhighlight lang="scala">// version 1.1.2
 
fun beadSort(a: IntArray) {
Sort of Integers:
Beforeval Sort:n = a.size
if (n < 2) return
[619,289,862,711,591,331,682,775,419,58,434,314,558,265,632,834,671,698,117,46]
var max = a.max()!!
val beads = ByteArray(max * n)
/* mark the beads */
for (i in 0 until n)
for (j in 0 until a[i])
beads[i * max + j] = 1
 
for (j in 0 until max) {
After Sort:
/* count how many beads are on each post */
[46,58,117,265,289,314,331,419,434,558,591,619,632,671,682,698,711,775,834,862]
var sum = 0
for (i in 0 until n) {
sum += beads[i * max + j]
beads[i * max + j] = 0
}
/* mark bottom sum beads */
for (i in n - sum until n) beads[i * max + j] = 1
}
 
for (i in 0 until n) {
var j = 0
while (j < max && beads[i * max + j] == 1.toByte()) j++
a[i] = j
}
}
 
fun main(args: Array<String>) {
val a = intArrayOf(5, 3, 1, 7, 4, 1, 1, 20)
println("Before sorting : ${a.contentToString()}")
beadSort(a)
println("After sorting : ${a.contentToString()}")
}</syntaxhighlight>
 
{{out}}
<pre>
Before sorting : [5, 3, 1, 7, 4, 1, 1, 20]
After sorting : [1, 1, 1, 3, 4, 5, 7, 20]
</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Display message followed by all values of a table in one line
function show (msg, t)
io.write(msg .. ":\t")
Line 1,209 ⟶ 1,871:
-- Main procedure
math.randomseed(os.time())
beadSort(randList(10, 1, 10))</langsyntaxhighlight>
{{out}}
<pre>Before sort: 9 5 3 9 4 1 3 8 1 2
Line 1,215 ⟶ 1,877:
After sort: 9 9 8 5 4 3 3 2 1 1</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">beadsort[ a ] := Module[ { m, sorted, s ,t },
 
sorted = a; m = Max[a]; t=ConstantArray[0, {m,m} ];
If[ Min[a] < 0, Print["can't sort"]];
For[ i = 1, i < Length[a], i++, t[[i,1;;a[[i]]]]=1 ]
 
For[ i = 1 ,i <= m, i++, s = Total[t[[;;,i]]];
t[[ ;; , i]] = 0; t[[1 ;; s , i]] = 1; ]
 
For[ i=1,i<=Length[a],i++, sorted[[i]] = Total[t[[i,;;]]]; ]
Print[sorted];
]
]</lang>
beadsort[{2,1,5,3,6}]</syntaxhighlight>
 
{{out}}
<pre>beadsort[{2,1,5,3,6}]
-<pre>{6,3,2,1,0}</pre>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,281 ⟶ 1,940:
end vv
return '['list.space(1, ',')']'
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,289 ⟶ 1,948:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc beadSort[T](a: var openarray[T]) =
var max = low(T)
var sum = 0
Line 1,298 ⟶ 1,957:
var beads = newSeq[int](max * a.len)
 
for i in 0 .. < a.len:
for j in 0 .. < a[i]:
beads[i * max + j] = 1
 
for j in 0 .. < max:
sum = 0
for i in 0 .. < a.len:
sum += beads[i * max + j]
beads[i * max + j] = 0
 
for i in a.len - sum .. < a.len:
beads[i * max + j] = 1
 
for i in 0 .. < a.len:
var j = 0
while j < max and beads[i * max + j] > 0: inc j
Line 1,318 ⟶ 1,977:
var a = @[5, 3, 1, 7, 4, 1, 1, 20]
beadSort a
echo a</langsyntaxhighlight>
{{out}}
<pre>@[1, 1, 1, 3, 4, 5, 7, 20]</pre>
Line 1,324 ⟶ 1,983:
=={{header|OCaml}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="ocaml">let rec columns l =
match List.filter ((<>) []) l with
[] -> []
Line 1,332 ⟶ 1,991:
 
let bead_sort l =
List.map List.length (columns (columns (List.map (fun e -> replicate e 1) l)))</langsyntaxhighlight>
usage
<pre>
Line 1,341 ⟶ 2,000:
=={{header|Octave}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="octave">function sorted = beadsort(a)
sorted = a;
m = max(a);
Line 1,361 ⟶ 2,020:
endfunction
 
beadsort([5, 7, 1, 3, 1, 1, 20])</langsyntaxhighlight>
 
=={{header|ooRexx}}==
===version 1===
<langsyntaxhighlight lang="oorexx">in='10 -12 1 0 999 8 2 2 4 4'
Do i=1 To words(in)
z.i=word(in,i)
Line 1,411 ⟶ 2,070:
End
Say ol
Return </langsyntaxhighlight>
{{out}}
<pre> Input: 10 -12 1 0 999 8 2 2 4 4
Line 1,419 ⟶ 2,078:
{{trans|REXX}}
'''Note:''' The only changes needed were to substitute '''<tt>_</tt>''', '''<tt>!</tt>''' and '''<tt>?</tt>''' characters for the &quot;deprecated&quot; <tt>'''$'''</tt>, <tt>'''#'''</tt> and '''<tt>@</tt>''' characters within variable names; as per <cite>The REXX Language, Second Edition</cite> by M. F. Cowlishaw. (See a description [http://www.rexxla.org/rexxlang/mfc/trl.html here]).
<langsyntaxhighlight ooRexxlang="oorexx">/*REXX program sorts a list of integers using a bead sort. */
 
/*get some grassHopper numbers. */
Line 1,501 ⟶ 2,160:
say copies('─',80) /*show a separator line. */
return
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,711 ⟶ 2,370:
=={{header|OpenEdge/Progress}}==
Sorting algorithms are not the kind of thing you need / want to do in OpenEdge. If you want to sort simply define a temp-table with one field, populate it and get sorted results with FOR EACH temp-table DESCENDING.
<langsyntaxhighlight lang="openedge/progress">FUNCTION beadSort RETURNS CHAR (
i_c AS CHAR
):
Line 1,761 ⟶ 2,420:
"5,3,1,7,4,1,1 -> " beadSort( "5,3,1,7,4,1,1" ) SKIP(1)
beadSort( "88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1" )
VIEW-AS ALERT-BOX.</langsyntaxhighlight>
{{out}}
<pre>---------------------------
Line 1,776 ⟶ 2,435:
=={{header|PARI/GP}}==
This implementation uses the counting sort to order the beads in a given row.
<langsyntaxhighlight lang="parigp">beadsort(v)={
my(sz=vecmax(v),M=matrix(#v,sz,i,j,v[i]>=j)); \\ Set up beads
for(i=1,sz,M[,i]=countingSort(M[,i],0,1)~); \\ Let them fall
Line 1,799 ⟶ 2,458:
);
left
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
See [[Sorting_algorithms/Bead_sort#Delphi | Delphi]]
program BDS;
const MAX = 1000;
type
type_matrix = record
lin,col:integer;
matrix: array [1..MAX,1..MAX] of boolean;
end;
 
type_vector = record
size:integer;
vector: array[1..MAX] of integer;
end;
 
procedure BeadSort(var v:type_vector);
var
i,j,k,sum:integer;
m:type_matrix;
begin
m.lin:=v.size;
 
(* the number of columns is equal to the greatest element *)
m.col:=0;
for i:=1 to v.size do
if v.vector[i] > m.col then
m.col:=v.vector[i];
 
(* initializing the matrix *)
for j:=1 to m.lin do
begin
k:=1;
for i:=m.col downto 1 do
begin
if v.vector[j] >= k then
m.matrix[i,j]:=TRUE
else
m.matrix[i,j]:=FALSE;
k:=k+1;
end;
end;
 
(* Sort the matrix *)
for i:=1 to m.col do
begin
(* Count the beads and set the line equal FALSE *)
sum:=0;
for j:=1 to m.lin do
begin
if m.matrix[i,j] then
sum:=sum+1;
m.matrix[i,j]:=FALSE;
end;
 
(* The line receives the bead sorted *)
for j:=m.lin downto m.lin-sum+1 do
m.matrix[i,j]:=TRUE;
end;
 
(* Convert the sorted bead matrix to a sorted vector *)
for j:=1 to m.lin do
begin
v.vector[j]:=0;
i:=m.col;
while (m.matrix[i,j] = TRUE)and(i>=1) do
begin
v.vector[j]+=1;
i:=i-1;
end;
end;
end;
 
procedure print_vector(var v:type_vector);
var i:integer;
begin
for i:=1 to v.size do
write(v.vector[i],' ');
writeln;
end;
 
var
i:integer;
v:type_vector;
begin
writeln('How many numbers do you want to sort?');
readln(v.size);
writeln('Write the numbers:');
 
for i:=1 to v.size do
read(v.vector[i]);
 
writeln('Before sort:');
print_vector(v);
 
BeadSort(v);
 
writeln('After sort:');
print_vector(v);
end.
 
</syntaxhighlight>
 
{{out}}
<pre>
How many numbers do you want to sort?
10
Write the numbers:
23 13 99 45 26 7 63 214 87 45
Before sort:
23 13 99 45 26 7 63 214 87 45
After sort:
7 13 23 26 45 45 63 87 99 214
</pre>
 
=={{header|Perl}}==
Instead of storing the bead matrix explicitly, I choose to store just the number of beads in each row and column, compacting on the fly. At all times, the sum of the row widths is equal to the sum column heights.
 
<langsyntaxhighlight lang="perl">sub beadsort {
my @data = @_;
 
Line 1,823 ⟶ 2,593:
 
beadsort 5, 7, 1, 3, 1, 1, 20;
</syntaxhighlight>
</lang>
 
=={{header|Perl 6}}==
{{Works with|rakudo|2016-05}}
{{trans|Haskell}}
<lang perl6># routine cribbed from List::Utils;
sub transpose(@list is copy) {
gather {
while @list {
my @heads;
if @list[0] !~~ Positional { @heads = @list.shift; }
else { @heads = @list.map({$_.shift unless $_ ~~ []}); }
@list = @list.map({$_ unless $_ ~~ []});
take [@heads];
}
}
}
 
sub beadsort(@l) {
(transpose(transpose(map {[1 xx $_]}, @l))).map(*.elems);
}
 
my @list = 2,1,3,5;
say beadsort(@list).perl;</lang>
 
{{out}}
<pre>(5, 3, 2, 1)</pre>
Here we simulate the dropping beads by using the <tt>push</tt> method.
<lang perl6>sub beadsort(*@list) {
my @rods;
for words ^«@list -> $x { @rods[$x].push(1) }
gather for ^@rods[0] -> $y {
take [+] @rods.map: { .[$y] // last }
}
}
 
say beadsort 2,1,3,5;</lang>
The <tt>^</tt> is the "upto" operator that gives a range of 0 up to (but not including) its endpoint. We use it as a hyperoperator (<tt>^«</tt>) to generate all the ranges of rod numbers we should drop a bead on, with the result that <tt>$x</tt> tells us which rod to drop each bead on. Then we use <tt>^</tt> again on the first rod to see how deep the beads are stacked, since they are guaranteed to be the deepest there. The <tt>[+]</tt> adds up all the beads that are found at level <tt>$y</tt>. The <tt>last</tt> short circuits the map so we don't have to look for all the missing beads at a given level, since the missing beads are all guaranteed to come after the existing beads at that level (because we always dropped left to right starting at rod 0).
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function beadsort(sequence a)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence poles = repeat(0,max(a))
for i=1 to length(a) do
for j=1 to a[i] do
poles[j] += 1
end for
end for
sequence res = repeat(0,length(a))
for i=1 to length(poles) do
for j=1 to poles[i] do
res[j] += 1
end for
end for
return res
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">beadsort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
?beadsort({5, 3, 1, 7, 4, 1, 1, 20})</lang>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">poles</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span>
<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;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">poles</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">poles</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]],</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">a</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: #000000;">0</span>
<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;">poles</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">poles</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">poles</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]],</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">beadsort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">20</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,887 ⟶ 2,620:
=={{header|PHP}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="php"><?php
function columns($arr) {
if (count($arr) == 0)
Line 1,907 ⟶ 2,640:
 
print_r(beadsort(array(5,3,1,7,4,1,1)));
?></langsyntaxhighlight>
 
{{out}}
Line 1,924 ⟶ 2,657:
The following implements a direct model of the bead sort algorithm.
Each pole is a list of 'T' symbols for the beads.
<langsyntaxhighlight PicoLisplang="picolisp">(de beadSort (Lst)
(let Abacus (cons NIL)
(for N Lst # Thread beads on poles
Line 1,932 ⟶ 2,665:
(make
(while (gt0 (cnt pop (cdr Abacus))) # Drop and count beads
(link @) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (beadSort (5 3 1 7 4 1 1 20))
Line 1,939 ⟶ 2,672:
=={{header|PL/I}}==
===version 1===
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Handles both negative and positive values. */
 
Line 2,012 ⟶ 2,745:
if offset < 0 then z = a + offset; else z = a;
 
end beadsort;</langsyntaxhighlight>
 
===version 2===
{{trans|ooRexx}}
PL/I supports negative array indices!
<langsyntaxhighlight lang="pli">*process source attributes xref;
/* Handles both negative and positive values. */
Beadsort: Proc Options(main);
Line 2,062 ⟶ 2,795:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre> Input: 10 -12 1 0 999 8 2 2 4 4
Line 2,068 ⟶ 2,801:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function BeadSort ( [Int64[]] $indata )
{
if( $indata.length -gt 1 )
Line 2,107 ⟶ 2,840:
}
 
$l = 100; BeadSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } )</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#MAXNUM=100
 
Dim MyData(Random(15)+5)
Line 2,181 ⟶ 2,914:
Next
PrintN(#CRLF$+"And its sum= "+Str(sum))
EndProcedure</langsyntaxhighlight>
<pre>
The array is;
Line 2,192 ⟶ 2,925:
 
=={{header|Python}}==
<syntaxhighlight lang="python">
{{trans|Haskell}}
#!/bin/python3
<lang python>try:
from itertools import zip_longest
except:
try:
from itertools import izip_longest as zip_longest
except:
zip_longest = lambda *args: map(None, *args)
 
# This is wrong, it works only on specific examples
def beadsort(l):
return list(map(lensum, columns(columnszip_longest(*[[1] * e for e in l], fillvalue=0)))
 
def columns(l):
return [filter(None, x) for x in zip_longest(*l)]
 
# Demonstration code:
print(beadsort([5,3,1,7,4,1,1]))</lang>
</syntaxhighlight>
 
{{out}}
<pre>[7, 5, 4, 3, 1, 1, 1]</pre>
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
#lang QB64
'***************************************************
'* BeadSort is VERY fast for small CGSortLibArray(max)-CGSortLibArray(min). Typical performance is
'* O(NlogN) or better. However as the key values (array values and ranges) go up, the performance
'* drops steeply excellent for small-ranged arrays. Integer only at this point. Throughput is
'* roughly 900k/GHzS for double-precision, with binary range (0,1). Related to CountingSort()
'***************************************************
SUB BeadSort (CGSortLibArray() AS DOUBLE, start AS LONG, finish AS LONG, order&)
DIM MAX AS DOUBLE: MAX = CGSortLibArray(start)
DIM BeadSort_Sum AS DOUBLE
DIM BeadSort_I AS LONG
DIM BeadSort_J AS LONG
FOR BeadSort_I = start + 1 TO (finish - start)
IF (CGSortLibArray(BeadSort_I) > MAX) THEN MAX = CGSortLibArray(BeadSort_I)
NEXT
REDIM beads((finish - start), MAX)
FOR BeadSort_I = 0 TO (finish - start) - 1
FOR BeadSort_J = 0 TO CGSortLibArray(BeadSort_I) - 1
beads(BeadSort_I, BeadSort_J) = 1
NEXT
NEXT
IF order& = 1 THEN
FOR BeadSort_J = 0 TO MAX
BeadSort_Sum = 0
FOR BeadSort_I = 0 TO (finish - start)
BeadSort_Sum = BeadSort_Sum + beads(BeadSort_I, BeadSort_J)
beads(BeadSort_I, BeadSort_J) = 0
NEXT
FOR BeadSort_I = (finish - start) - BeadSort_Sum TO (finish - start)
beads(BeadSort_I, BeadSort_J) = 1
NEXT
NEXT
FOR BeadSort_I = 0 TO (finish - start)
BeadSort_J = 0
WHILE BeadSort_J < MAX AND beads(BeadSort_I, BeadSort_J)
BeadSort_J = BeadSort_J + 1
WEND
CGSortLibArray(BeadSort_I) = BeadSort_J
NEXT
ELSE
FOR BeadSort_J = MAX TO 0 STEP -1
BeadSort_Sum = 0
FOR I = 0 TO (finish - start)
BeadSort_Sum = BeadSort_Sum + beads(I, BeadSort_J)
beads(I, BeadSort_J) = 0
NEXT
FOR I = (finish - start) TO (finish - start) - BeadSort_Sum STEP -1
beads(I, BeadSort_J) = 1
NEXT
NEXT
FOR BeadSort_I = 0 TO (finish - start)
BeadSort_J = 0
WHILE BeadSort_J < MAX AND beads(BeadSort_I, BeadSort_J)
BeadSort_J = BeadSort_J + 1
WEND
CGSortLibArray(finish - BeadSort_I) = BeadSort_J
NEXT
END IF
END SUB
</syntaxhighlight>
 
=={{header|Racket}}==
 
{{trans|Haskell}}
<syntaxhighlight lang="racket">
 
<lang racket>
#lang racket
(require rackunit)
Line 2,233 ⟶ 3,022:
(bead-sort '(5 3 1 7 4 1 1))
'(7 5 4 3 1 1 1))
</syntaxhighlight>
</lang>
 
=={{header|REXXRaku}}==
(formerly Perl 6)
The REXX language has the advantage of supporting sparse arrays, so implementing a bead sort is trivial, the major
{{Works with|rakudo|2016-05}}
<br>drawback is if the spread &nbsp; (difference between the lowest and highest values) &nbsp; is quite large will slow up the display.
{{trans|Haskell}}
<syntaxhighlight lang="raku" line># routine cribbed from List::Utils;
sub transpose(@list is copy) {
gather {
while @list {
my @heads;
if @list[0] !~~ Positional { @heads = @list.shift; }
else { @heads = @list.map({$_.shift unless $_ ~~ []}); }
@list = @list.map({$_ unless $_ ~~ []});
take [@heads];
}
}
}
 
sub beadsort(@l) {
Negative and duplicate integers (values) can be handled.
(transpose(transpose(map {[1 xx $_]}, @l))).map(*.elems);
<lang rexx>/*REXX program sorts a list of integers using the bead sort algorithm. */
}
grasshopper=, /*define two dozen grasshopper numbers.*/
1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270
 
my @list = 2,1,3,5;
/*Green Grocer numbers are also called hexagonal pyramidal numbers.*/
say beadsort(@list).perl;</syntaxhighlight>
greenGrocer= 0 4 16 40 80 140 224 336 480 660 880 1144 1456 1820 2240 2720 3264 3876 4560
 
{{out}}
/*define 23 Bernoulli numerator numbers*/
<pre>(5, 3, 2, 1)</pre>
bernN= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 0 854513'
Here we simulate the dropping beads by using the <tt>push</tt> method.
<syntaxhighlight lang="raku" line>sub beadsort(*@list) {
my @rods;
for words ^«@list -> $x { @rods[$x].push(1) }
gather for ^@rods[0] -> $y {
take [+] @rods.map: { .[$y] // last }
}
}
 
say beadsort 2,1,3,5;</syntaxhighlight>
/*Psi is also called the Reduced Totient function, and is*/
The <tt>^</tt> is the "upto" operator that gives a range of 0 up to (but not including) its endpoint. We use it as a hyperoperator (<tt>^«</tt>) to generate all the ranges of rod numbers we should drop a bead on, with the result that <tt>$x</tt> tells us which rod to drop each bead on. Then we use <tt>^</tt> again on the first rod to see how deep the beads are stacked, since they are guaranteed to be the deepest there. The <tt>[+]</tt> adds up all the beads that are found at level <tt>$y</tt>. The <tt>last</tt> short circuits the map so we don't have to look for all the missing beads at a given level, since the missing beads are all guaranteed to come after the existing beads at that level (because we always dropped left to right starting at rod 0).
psi=, /*also called Carmichael lambda, or the LAMBDA function.*/
1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 10 22 2 20 12 18 6 28 4 30 8 10 16
 
=={{header|REXX}}==
#= grasshopper greenGrocer bernN psi /*combine the four lists into one list.*/
The REXX language has the advantage of supporting sparse arrays, so implementing a bead sort is trivial, the
call show 'before sort', # /*display the list before sorting. */
<br>major drawback is &nbsp; ''if'' &nbsp; the spread &nbsp; (difference between the lowest and highest values) &nbsp; is quite large &nbsp; (if it's
call show ' after sort', beadSort(#) /* " " " after " */
<br>greater than a few million), &nbsp; it'll slow up the display &nbsp; (but not the sorting).
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
beadSort: procedure; parse arg low . 1 high . 1 z,$ /*$: the list to be sorted. */
@.=0 /*set all beads (@.) to zero.*/
do j=1 until z==''; parse var z x z /*pick the meat off the bone.*/
if \datatype(x, 'W') then do; say '***error***'
say 'element' j "in list isn't numeric:" x
say; exit 13
end /* [↑] exit pgm with RC=13. */
x=x/1 /*normalize: 4. 004 +4 .4e0 */
@.x=@.x+1 /*indicate this bead has a #.*/
low=min(low,x); high=max(high,x) /*track lowest and highest #.*/
end /*j*/
/* [↓] now, collect beads and*/
do m=low to high /*let them fall (to zero). */
if @.m\==0 then do n=1 for @.m; $=$ m /*have we found a bead here? */
end /*n*/ /* [↑] add it to sorted list*/
end /*m*/
 
Zero, negative, and duplicate integers (values) can be handled.
return $
<syntaxhighlight lang="rexx">/*REXX program sorts a list (4 groups) of integers using the bead sort algorithm. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show:/* parseoriginal argsource txt,y;by Gerard Schildberger _=left('', 20) */
/* 20230605 Walter Pachl reformatted and refurbished w=length(words(y)); do k=1 for words(y) /* [↑] twenty pad blanks. */
say _ 'element' /* right(k,define w) two dozen txt":" grasshopper right(word(y,numbers. k), 9) */
end /*k source ?? */
gHopper=1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254,
say copies('─', 70) /*show a long separator line.*/
return</lang> 270
/* these are also called hexagonal pyramidal #s. */
'''output''' &nbsp; when using the default (internal) numbers:
/* see https://oeis.org/A002412 */
<pre style="height:60ex">
greenGrocer=0 4 16 40 80 140 224 336 480 660 880 1144 1456 1820 2240 2720 3264 3876,
element 1 before sort: 1
4560
element 2 before sort: 4
element 3 before sort: /* 10define twenty-three Bernoulli numerator numbers*/
element 4 before sort: /* 12source ?? quotes needed because of negative #s.*/
bernN='1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 element 5 before sort: 220'
element 6 before sort: /* 26also called the Reduced Totient function, */
element 7 before sort: /* 30and is also called Carmichael lambda, */
element 8 before sort: /* 46or the LAMBDA function */
element 9 before sort: /* see https://en.wikipedia.org/wiki/Carmichael_function 54*/
psi=1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 element10 22 102 before20 sort:12 18 6 28 4 30 8 10 6216
list=gHopper greenGrocer bernN psi /*combine the four lists into one list.*/
element 11 before sort: 66
Call show 'before sort',list /*display elementthe 12list before sort: sorting. 78*/
Say copies('¦', 75) element 13 before sort: /*show long separator line before 94sort.*/
Call show ' after sort',beadSort(list) /*display the list after sorting. */
element 14 before sort: 110
Exit element 15 before sort: 126 /*stick a fork in it, we're all done. */
/*----------------------------------------------------------------------------------*/
element 16 before sort: 134
beadSort: Procedure
element 17 before sort: 138
Parse Arg list 1 low . 1 high . element /* 18List beforeto sort:be sorted and first value 158*/
occurences.=0 element 19 before sort: 162/* count stem occurences */
Do Until list=='' element 20 before sort: /* loop 186through the list */
Parse Var list bead list /* take an element 21 before sort: 190 */
bead= bead / 1 element 22 before sort: 222 /* normalize the value */
occurences.bead=occurences.bead + 1 /* bump occurences element 23 before sort: 254 */
low= min(low, bead) element 24 before sort: /* track lowest 270 */
high=max(high,bead) element 25 before sort: /* and highest number 0 */
End
element 26 before sort: 4
sorted='' element 27 before sort: 16 /* now, collect the beads */
Do v=low To high
element 28 before sort: 40
If occurences.v>0 Then
element 29 before sort: 80
sorted=sorted copies(v' ', occurences.v)
element 30 before sort: 140
End
element 31 before sort: 224
Return sorted
element 32 before sort: 336
/*----------------------------------------------------------------------------------*/
element 33 before sort: 480
show:
element 34 before sort: 660
Parse Arg txt,slist
element 35 before sort: 880
n=words(slist)
element 36 before sort: 1144
w=length(n)
element 37 before sort: 1456
Do k=1 For n
element 38 before sort: 1820
Say right('element',30) right(k,w) txt':' right(word(slist,k),9)
element 39 before sort: 2240
End
element 40 before sort: 2720
Return</syntaxhighlight>
element 41 before sort: 3264
{{out|output|text=&nbsp; when using the default input:}}
element 42 before sort: 3876
(Shown at three-quarter size.)
element 43 before sort: 4560
<pre style="font-size:75%;height:90ex">
element 44 before sort: 1
element 451 before sort: - 1
element 462 before sort: 14
element 473 before sort: 010
element 484 before sort: -112
element 495 before sort: 022
element 506 before sort: 126
element 517 before sort: 030
element 528 before sort: -146
element 539 before sort: 054
element 54element 10 before sort: 562
element 55element 11 before sort: 066
element 56element 12 before sort: -691 78
element 57element 13 before sort: 094
element 5814 before sort: 7110
element 5915 before sort: 0126
element 60element 16 before sort: -3617 134
element 6117 before sort: 0138
element 62element 18 before sort: 43867 158
element 6319 before sort: 0162
element 64element 20 before sort: -174611 186
element 6521 before sort: 0190
element 66element 22 before sort: 854513 222
element 6723 before sort: 1254
element 6824 before sort: 1270
element 69element 25 before sort: 20
element 70element 26 before sort: 24
element 71element 27 before sort: 416
element 72element 28 before sort: 240
element 73element 29 before sort: 680
element 7430 before sort: 2140
element 7531 before sort: 6224
element 7632 before sort: 4336
element 77element 33 before sort: 10480
element 7834 before sort: 2660
element 79element 35 before sort: 12880
element 8036 before sort: 61144
element 8137 before sort: 41456
element 8238 before sort: 41820
element 8339 before sort: 162240
element 8440 before sort: 62720
element 8541 before sort: 183264
element 8642 before sort: 43876
element 8743 before sort: 64560
element 88element 44 before sort: 10 1
element 89element 45 before sort: 22-1
element 90element 46 before sort: 21
element 91element 47 before sort: 20 0
element 92element 48 before sort: 12-1
element 93element 49 before sort: 18 0
element 94element 50 before sort: 61
element 95element 51 before sort: 28 0
element 96element 52 before sort: 4-1
element 97element 53 before sort: 30 0
element 98element 54 before sort: 85
element 99element 55 before sort: 10 0
element 10056 before sort: 16-691
element 57 before sort: 0
──────────────────────────────────────────────────────────────────────
element element 158 afterbefore sort: -174611 7
element element 259 afterbefore sort: -3617 0
element element 360 afterbefore sort: -6913617
element element 461 afterbefore sort: -1 0
element element 562 afterbefore sort: -143867
element element 663 afterbefore sort: -1 0
element element 764 afterbefore sort: 0-174611
element element 8 65 afterbefore sort: 0
element element 9 66 afterbefore sort: 01
element 10element 67 afterbefore sort: 01
element 11element 68 afterbefore sort: 02
element 12element 69 afterbefore sort: 02
element 13element 70 afterbefore sort: 04
element 14element 71 afterbefore sort: 02
element 15element 72 afterbefore sort: 06
element 16element 73 afterbefore sort: 02
element 17element 74 afterbefore sort: 06
element 18element 75 afterbefore sort: 14
element 19element 76 afterbefore sort: 110
element 20element 77 afterbefore sort: 12
element 21element 78 afterbefore sort: 112
element 22element 79 afterbefore sort: 16
element 23element 80 afterbefore sort: 14
element 24element 81 afterbefore sort: 24
element 25element 82 afterbefore sort: 216
element 26element 83 afterbefore sort: 26
element 27element 84 afterbefore sort: 218
element 28element 85 afterbefore sort: 24
element 29element 86 afterbefore sort: 26
element 30element 87 afterbefore sort: 410
element 31element 88 afterbefore sort: 422
element 32element 89 afterbefore sort: 42
element 33element 90 afterbefore sort: 420
element 34element 91 afterbefore sort: 412
element 35element 92 afterbefore sort: 418
element 36element 93 afterbefore sort: 46
element 37element 94 afterbefore sort: 428
element 38element 95 afterbefore sort: 54
element 39element 96 afterbefore sort: 630
element 40element 97 afterbefore sort: 68
element 41element 98 afterbefore sort: 610
element 42element 99 afterbefore sort: 616
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
element 43 after sort: 6
element 441 after sort: 6-174611
element 452 after sort: 7-3617
element 463 after sort: 8-691
element 474 after sort: 10-1
element 485 after sort: 10-1
element 496 after sort: 10-1
element 507 after sort: 10 0
element 518 after sort: 12 0
element 529 after sort: 12 0
element 53element 10 after sort: 12 0
element 54element 11 after sort: 16 0
element 55element 12 after sort: 16 0
element 56element 13 after sort: 16 0
element 57element 14 after sort: 18 0
element 58element 15 after sort: 18 0
element 59element 16 after sort: 20 0
element 60element 17 after sort: 22 0
element 61element 18 after sort: 22 1
element 62element 19 after sort: 26 1
element 63element 20 after sort: 28 1
element 64element 21 after sort: 30 1
element 65element 22 after sort: 30 1
element 66element 23 after sort: 40 1
element 67element 24 after sort: 46 2
element 68element 25 after sort: 54 2
element 69element 26 after sort: 62 2
element 70element 27 after sort: 66 2
element 71element 28 after sort: 78 2
element 72element 29 after sort: 80 2
element 73element 30 after sort: 94 4
element 74element 31 after sort: 110 4
element 75element 32 after sort: 126 4
element 76element 33 after sort: 134 4
element 77element 34 after sort: 138 4
element 78element 35 after sort: 140 4
element 79element 36 after sort: 158 4
element 80element 37 after sort: 162 4
element 81element 38 after sort: 186 5
element 82element 39 after sort: 190 6
element 83element 40 after sort: 222 6
element 84element 41 after sort: 224 6
element 85element 42 after sort: 254 6
element 86element 43 after sort: 270 6
element 87element 44 after sort: 336 6
element 88element 45 after sort: 480 7
element 89element 46 after sort: 660 8
element 90element 47 after sort: 880 10
element 91element 48 after sort: 1144 10
element 92element 49 after sort: 1456 10
element 93element 50 after sort: 1820 10
element 94element 51 after sort: 2240 12
element 95element 52 after sort: 2720 12
element 96element 53 after sort: 3264 12
element 97element 54 after sort: 3876 16
element 98element 55 after sort: 4560 16
element 99element 56 after sort: 43867 16
element 10057 after sort: 854513 18
element 58 after sort: 18
──────────────────────────────────────────────────────────────────────
element 59 after sort: 20
element 60 after sort: 22
element 61 after sort: 22
element 62 after sort: 26
element 63 after sort: 28
element 64 after sort: 30
element 65 after sort: 30
element 66 after sort: 40
element 67 after sort: 46
element 68 after sort: 54
element 69 after sort: 62
element 70 after sort: 66
element 71 after sort: 78
element 72 after sort: 80
element 73 after sort: 94
element 74 after sort: 110
element 75 after sort: 126
element 76 after sort: 134
element 77 after sort: 138
element 78 after sort: 140
element 79 after sort: 158
element 80 after sort: 162
element 81 after sort: 186
element 82 after sort: 190
element 83 after sort: 222
element 84 after sort: 224
element 85 after sort: 254
element 86 after sort: 270
element 87 after sort: 336
element 88 after sort: 480
element 89 after sort: 660
element 90 after sort: 880
element 91 after sort: 1144
element 92 after sort: 1456
element 93 after sort: 1820
element 94 after sort: 2240
element 95 after sort: 2720
element 96 after sort: 3264
element 97 after sort: 3876
element 98 after sort: 4560
element 99 after sort: 43867
</pre>
 
=={{header|Ruby}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="ruby">class Array
def beadsort
map {|e| [1] * e}.columns.columns.map(&:length)
Line 2,507 ⟶ 3,339:
 
# Demonstration code:
p [5,3,1,7,4,1,1].beadsort</langsyntaxhighlight>
 
{{out}}
Line 2,513 ⟶ 3,345:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: beadSort (inout array integer: a) is func
Line 2,534 ⟶ 3,366:
for i range 1 to length(a) do
sum +:= ord(j in beads[i]);
excl(beads[i], j);
end for;
for i range length(a) downto length(a) - sum + 1 to length(a) do
incl(beadsa[i], := j);
end for;
end for;
for i range 1 to length(a) do
for j range 1 to max until j not in beads[i] do
noop;
end for;
a[i] := pred(j);
end for;
end func;
Line 2,551 ⟶ 3,376:
local
var array integer: a is [] (5, 3, 1, 7, 4, 1, 1, 20);
var integer: numn is 0;
begin
beadSort(a);
for numn range a do
write(numn <& " ");
end for;
writeln;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,567 ⟶ 3,392:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func beadsort(arr) {
 
var rows = [];
var columns = [];
 
for datum in arr.each { |datum|
range(0,for column in ^datum-1).each { |column|
++(columns[column] := 0);
++(rows[columns[column] - 1] := 0);
}
}
 
rows.reverse;
}
 
say beadsort([5,3,1,7,4,1,1]);</langsyntaxhighlight>
 
{{out}}
Line 2,591 ⟶ 3,416:
=={{header|Standard ML}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="sml">fun columns l =
case List.filter (not o null) l of
[] => []
Line 2,599 ⟶ 3,424:
 
fun bead_sort l =
map length (columns (columns (map (fn e => replicate (e, 1)) l)))</langsyntaxhighlight>
usage
<pre>
Line 2,607 ⟶ 3,432:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc beadsort numList {
Line 2,629 ⟶ 3,454:
 
# Demonstration code
puts [beadsort {5 3 1 7 4 1 1}]</langsyntaxhighlight>
{{out}}
<pre>7 5 4 3 1 1 1</pre>
 
=={{header|VBA}}==
{{trans|Phix}}<syntaxhighlight lang="vb">Option Base 1
 
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
 
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
ReDim poles(WorksheetFunction.Max(a))
For i = 1 To UBound(a)
For j = 1 To a(i)
poles(j) = poles(j) + 1
Next j
Next i
For j = 1 To UBound(a)
a(j) = 0
Next j
For i = 1 To UBound(poles)
For j = 1 To poles(i)
a(j) = a(j) + 1
Next j
Next i
beadsort = a
End Function
Public Sub main()
Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ")
End Sub</syntaxhighlight>{{out}}
<pre>20, 7, 5, 4, 3, 1, 1, 1</pre>
 
=={{header|Wren}}==
A translation of the Python code in the Wikipedia article. Only works properly for lists of non-negative integers.
<syntaxhighlight lang="wren">var beadSort = Fn.new { |a|
var res = []
var max = a.reduce { |acc, i| (i > acc) ? i : acc }
var trans = [0] * max
for (i in a) {
for (n in 0...i) trans[n] = trans[n] + 1
}
for (i in a) {
res.add(trans.count { |n| n > 0 })
for (n in 0...trans.count) trans[n] = trans[n] - 1
}
return res[-1..0] // return in ascending order
}
 
var array = [ [4, 65, 2, 31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in array) {
System.print("Before: %(a)")
a = beadSort.call(a)
System.print("After : %(a)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Before: [4, 65, 2, 31, 0, 99, 2, 83, 782, 1]
After : [0, 1, 2, 2, 4, 31, 65, 83, 99, 782]
 
Before: [7, 5, 2, 6, 1, 4, 2, 6, 3]
After : [1, 2, 2, 3, 4, 5, 6, 6, 7]
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
proc BeadSort(Array, Length); \Sort Array into increasing order
Line 2,660 ⟶ 3,554:
BeadSort(A, 10);
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
]</langsyntaxhighlight>
 
{{out}}
Line 2,669 ⟶ 3,563:
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn columns(m){ // m is list of lists of zeros/beads, # beads is n, eg (0,0,0)==3
m
.apply("len") // (0,0,0)-->3
Line 2,679 ⟶ 3,573:
fcn beadSort(data){
data.apply("pump",List,0):columns(_):columns(_).apply("len");
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">T(5,3,1,7,4,1,1):beadSort(_).println();
T(4,3,3,2,1):beadSort(_).println();</langsyntaxhighlight>
{{out}}
<pre>
9,482

edits