Sort an integer array: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Wren)
m (→‎{{header|Wren}}: Minor tidy)
 
(31 intermediate revisions by 23 users not shown)
Line 1: Line 1:
{{task|Sorting}}
{{task|Sorting}}
{{Sorting Algorithm}}
Sort an array (or list) of integers in ascending numerical order.


;Task:
;Task:
Sort an array (or list) of integers in ascending numerical order.


Use a sorting facility provided by the language/library if possible.
Use a sorting facility provided by the language/library if possible.
<br><br>
<br><br>

=={{header|11l}}==
{{trans|Python}}

<syntaxhighlight lang="11l">nums = [2,4,3,1,2]
nums.sort()</syntaxhighlight>
You could also use the built-in sorted() function:
<syntaxhighlight lang="11l">nums = sorted([2,4,3,1,2])</syntaxhighlight>


=={{header|4D}}==
=={{header|4D}}==
===English===
===English===


<lang 4d>ARRAY INTEGER($nums;0)
<syntaxhighlight lang="4d">ARRAY INTEGER($nums;0)
APPEND TO ARRAY($nums;2)
APPEND TO ARRAY($nums;2)
APPEND TO ARRAY($nums;4)
APPEND TO ARRAY($nums;4)
Line 16: Line 27:
APPEND TO ARRAY($nums;2)
APPEND TO ARRAY($nums;2)
SORT ARRAY($nums) ` sort in ascending order
SORT ARRAY($nums) ` sort in ascending order
SORT ARRAY($nums;<) ` sort in descending order</lang>
SORT ARRAY($nums;<) ` sort in descending order</syntaxhighlight>


===Français===
===Français===


<lang 4d>TABLEAU ENTIER($nombres;0)
<syntaxhighlight lang="4d">TABLEAU ENTIER($nombres;0)
AJOUTER A TABLEAU($nombres;2)
AJOUTER A TABLEAU($nombres;2)
AJOUTER A TABLEAU($nombres;4)
AJOUTER A TABLEAU($nombres;4)
Line 27: Line 38:
AJOUTER A TABLEAU($nombres;2)
AJOUTER A TABLEAU($nombres;2)
TRIER TABLEAU($nombres) ` pour effectuer un tri par ordre croissant
TRIER TABLEAU($nombres) ` pour effectuer un tri par ordre croissant
TRIER TABLEAU($nombres;<) ` pour effectuer un tri par ordre décroissant</lang>
TRIER TABLEAU($nombres;<) ` pour effectuer un tri par ordre décroissant</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang="forth">
[ 10,2,100 ] ' n:cmp a:sort . cr
[ 10,2,100 ] ' n:cmp a:sort . cr
</syntaxhighlight>
</lang>
Output is: [2,10,100]
Output is: [2,10,100]
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program integerSort64.s with selection 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
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0
mov x2,NBELEMENTS // number of élements
bl selectionSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
beq 1f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
1: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* selection sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
selectionSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x3,x1 // start index i
sub x7,x2,1 // compute n - 1
1: // start loop
mov x4,x3
add x5,x3,1 // init index 2
2:
ldr x1,[x0,x4,lsl 3] // load value A[mini]
ldr x6,[x0,x5,lsl 3] // load value A[j]
cmp x6,x1 // compare value
csel x4,x5,x4,lt // j -> mini
add x5,x5,1 // increment index j
cmp x5,x2 // end ?
blt 2b // no -> loop
cmp x4,x3 // mini <> j ?
beq 3f // no
ldr x1,[x0,x4,lsl 3] // yes swap A[i] A[mini]
ldr x6,[x0,x3,lsl 3]
str x1,[x0,x3,lsl 3]
str x6,[x0,x4,lsl 3]
3:
add x3,x3,1 // increment i
cmp x3,x7 // end ?
blt 1b // no -> loop
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

</syntaxhighlight>
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit

PROC PrintArray(INT ARRAY a INT size)
INT i

Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN

PROC Test(INT ARRAY a INT size BYTE order)
PrintE("Array before sort:")
PrintArray(a,size)
SortI(a,size,order)
PrintE("Array after sort:")
PrintArray(a,size)
PutE()
RETURN

PROC Main()
DEFINE ASCENDING="0"
INT ARRAY
a(10)=[1 4 65535 0 3 7 4 8 20 65530],
b(21)=[10 9 8 7 6 5 4 3 2 1 0
65535 65534 65533 65532 65531
65530 65529 65528 65527 65526],
c(8)=[101 102 103 104 105 106 107 108],
d(12)=[1 65535 1 65535 1 65535 1
65535 1 65535 1 65535]
Put(125) PutE() ;clear screen
Test(a,10,ASCENDING)
Test(b,21,ASCENDING)
Test(c,8,ASCENDING)
Test(d,12,ASCENDING)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_an_integer_array.png Screenshot from Atari 8-bit computer]
<pre>
Array before sort:
[1 4 -1 0 3 7 4 8 20 -6]
Array after sort:
[-6 -1 0 1 3 4 4 7 8 20]

Array before sort:
[10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10]
Array after sort:
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]

Array before sort:
[101 102 103 104 105 106 107 108]
Array after sort:
[101 102 103 104 105 106 107 108]

Array before sort:
[1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
Array after sort:
[-1 -1 -1 -1 -1 -1 1 1 1 1 1 1]
</pre>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang ActionScript>//Comparison function must returns Numbers even though it deals with integers.
<syntaxhighlight lang="actionscript">//Comparison function must returns Numbers even though it deals with integers.
function compare(x:int, y:int):Number
function compare(x:int, y:int):Number
{
{
Line 42: Line 287:
}
}
var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]);
var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]);
nums.sort(compare);</lang>
nums.sort(compare);</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2006}}
{{works with|GNAT|GPL 2006}}
<lang ada>with Gnat.Heap_Sort_G;
<syntaxhighlight lang="ada">with Gnat.Heap_Sort_G;
procedure Integer_Sort is
procedure Integer_Sort is
Line 88: Line 333:
begin
begin
Sort(Values);
Sort(Values);
end Integer_Sort;</lang>
end Integer_Sort;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 96: Line 341:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>CO PR READ "shell_sort.a68" PR CO
<syntaxhighlight lang="algol68">CO PR READ "shell_sort.a68" PR CO
MODE TYPE = INT;
MODE TYPE = INT;


Line 119: Line 364:
in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq);
in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq);


print((shell sort((2, 4, 3, 1, 2)), new line))</lang>
print((shell sort((2, 4, 3, 1, 2)), new line))</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 127: Line 372:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Algol W doesn't have standard sorting facilities. This uses the Algol W quicksort sample in the Sorting Algorithms Quicksort task.
Algol W doesn't have standard sorting facilities. This uses the Algol W quicksort sample in the Sorting Algorithms Quicksort task.
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% use the quicksort procedure from the Sorting_Algorithms/Quicksort task %
% use the quicksort procedure from the Sorting_Algorithms/Quicksort task %
% Quicksorts in-place the array of integers v, from lb to ub - external %
% Quicksorts in-place the array of integers v, from lb to ub - external %
Line 142: Line 387:
for i := 1 until 5 do writeon( i_w := 1, s_w := 1, t( i ) )
for i := 1 until 5 do writeon( i_w := 1, s_w := 1, t( i ) )
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 150: Line 395:
=={{header|APL}}==
=={{header|APL}}==
{{works with|APL2}}
{{works with|APL2}}
<lang apl> X←63 92 51 92 39 15 43 89 36 69
<syntaxhighlight lang="apl"> X←63 92 51 92 39 15 43 89 36 69
X[⍋X]
X[⍋X]
15 36 39 43 51 63 69 89 92 92</lang>
15 36 39 43 51 63 69 89 92 92</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 164: Line 409:
for which AppleScript was presumably designed.
for which AppleScript was presumably designed.


<lang AppleScript>use framework "Foundation"
<syntaxhighlight lang="applescript">use framework "Foundation"


-- sort :: [a] -> [a]
-- sort :: [a] -> [a]
Line 206: Line 451:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9},
<pre>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9},
{"alpha", "beta", "delta", "epsilon", "eta", "gamma",
{"alpha", "beta", "delta", "epsilon", "eta", "gamma",
"iota", "kappa", "lambda", "mu", "theta", "zeta"}}</pre>
"iota", "kappa", "lambda", "mu", "theta", "zeta"}}</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">


/* ARM assembly Raspberry PI */
=={{header|Arturo}}==
/* program integerSort.s with selection 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"


/*********************************/
<lang arturo>arr: #(2 3 5 8 4 1 6 9 7)
/* Initialized data */
sort! arr // in-place
/*********************************/

.data
loop arr => print</lang>
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
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#0
mov r2,#NBELEMENTS @ number of élements
bl selectionSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 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]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/******************************************************************/
/* selection sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
selectionSort:
push {r1-r7,lr} @ save registers
mov r3,r1 @ start index i
sub r7,r2,#1 @ compute n - 1
1: @ start loop
mov r4,r3
add r5,r3,#1 @ init index 2
2:
ldr r1,[r0,r4,lsl #2] @ load value A[mini]
ldr r6,[r0,r5,lsl #2] @ load value A[j]
cmp r6,r1 @ compare value
movlt r4,r5 @ j -> mini
add r5,#1 @ increment index j
cmp r5,r2 @ end ?
blt 2b @ no -> loop
cmp r4,r3 @ mini <> j ?
beq 3f @ no
ldr r1,[r0,r4,lsl #2] @ yes swap A[i] A[mini]
ldr r6,[r0,r3,lsl #2]
str r1,[r0,r3,lsl #2]
str r6,[r0,r4,lsl #2]
3:
add r3,#1 @ increment i
cmp r3,r7 @ end ?
blt 1b @ no -> loop
100:
pop {r1-r7,lr}
bx lr @ return
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsZoneConv @
bl conversion10 @ décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r3,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">arr: [2 3 5 8 4 1 6 9 7]
sort 'arr ; in-place
loop arr => print</syntaxhighlight>


{{out}}
{{out}}
Line 233: Line 637:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>numbers = 5 4 1 2 3
<syntaxhighlight lang="autohotkey">numbers = 5 4 1 2 3
sort, numbers, N D%A_Space%
sort, numbers, N D%A_Space%
Msgbox % numbers</lang>
Msgbox % numbers</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SORT_AN_INTEGER_ARRAY.AWK
# syntax: GAWK -f SORT_AN_INTEGER_ARRAY.AWK
BEGIN {
BEGIN {
Line 254: Line 658:
printf("\t%s\n",description)
printf("\t%s\n",description)
}
}
</syntaxhighlight>
</lang>
<p>output:</p>
<p>output:</p>
<pre>
<pre>
Line 265: Line 669:
There is no ascending sort function in Axe, but there is a descending sort function. One can either implement a custom ascending sorting function or simply reverse the output from SortD.
There is no ascending sort function in Axe, but there is a descending sort function. One can either implement a custom ascending sorting function or simply reverse the output from SortD.


<lang axe>2→{L₁}
<syntaxhighlight lang="axe">2→{L₁}
4→{L₁+1}
4→{L₁+1}
3→{L₁+2}
3→{L₁+2}
Line 271: Line 675:
2→{L₁+4}
2→{L₁+4}


SortD(L₁,5)</lang>
SortD(L₁,5)</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
Line 277: Line 681:
Use the sortval operator to sort an array of integers (val-array in Babel terminology). The following code creates a list of random values, converts it to a val-array, sorts that val-array, then converts it back to a list for display using the lsnum utility.
Use the sortval operator to sort an array of integers (val-array in Babel terminology). The following code creates a list of random values, converts it to a val-array, sorts that val-array, then converts it back to a list for display using the lsnum utility.


<lang babel>babel> nil { zap {1 randlf 100 rem} 20 times collect ! } nest dup lsnum ! --> Create a list of random numbers
<syntaxhighlight lang="babel">babel> nil { zap {1 randlf 100 rem} 20 times collect ! } nest dup lsnum ! --> Create a list of random numbers
( 20 47 69 71 18 10 92 9 56 68 71 92 45 92 12 7 59 55 54 24 )
( 20 47 69 71 18 10 92 9 56 68 71 92 45 92 12 7 59 55 54 24 )
babel> ls2lf --> Convert list to array for sorting
babel> ls2lf --> Convert list to array for sorting
babel> dup {fnord} merge_sort --> The internal sort operator
babel> dup {fnord} merge_sort --> The internal sort operator
babel> ar2ls lsnum ! --> Display the results
babel> ar2ls lsnum ! --> Display the results
( 7 9 10 12 18 20 24 45 47 54 55 56 59 68 69 71 71 92 92 92 )</lang>
( 7 9 10 12 18 20 24 45 47 54 55 56 59 68 69 71 71 92 92 92 )</syntaxhighlight>


In Babel, lists and arrays are distinct. If you want to sort a list, use the lssort utility:
In Babel, lists and arrays are distinct. If you want to sort a list, use the lssort utility:


<lang babel>babel> ( 68 73 63 83 54 67 46 53 88 86 49 75 89 83 28 9 34 21 20 90 )
<syntaxhighlight lang="babel">babel> ( 68 73 63 83 54 67 46 53 88 86 49 75 89 83 28 9 34 21 20 90 )
babel> {lt?} lssort ! lsnum !
babel> {lt?} lssort ! lsnum !
( 9 20 21 28 34 46 49 53 54 63 67 68 73 75 83 83 86 88 89 90 )</lang>
( 9 20 21 28 34 46 49 53 54 63 67 68 73 75 83 83 86 88 89 90 )</syntaxhighlight>


To reverse the sort-order, use the 'gt?' predicate instead of the 'lt?' predicate:
To reverse the sort-order, use the 'gt?' predicate instead of the 'lt?' predicate:


<lang babel>babel> ( 68 73 63 83 54 67 46 53 88 86 49 75 89 83 28 9 34 21 20 90 ) {gt?} lssort ! lsnum !
<syntaxhighlight lang="babel">babel> ( 68 73 63 83 54 67 46 53 88 86 49 75 89 83 28 9 34 21 20 90 ) {gt?} lssort ! lsnum !
( 90 89 88 86 83 83 75 73 68 67 63 54 53 49 46 34 28 21 20 9 )</lang>
( 90 89 88 86 83 83 75 73 68 67 63 54 53 49 46 34 28 21 20 9 )</syntaxhighlight>


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang freebasic>' Sort an integer array
<syntaxhighlight lang="freebasic">' Sort an integer array
DECLARE values[5] TYPE NUMBER
DECLARE values[5] TYPE NUMBER
values[0] = 23
values[0] = 23
Line 309: Line 713:
PRINT values[i], ", ";
PRINT values[i], ", ";
NEXT
NEXT
PRINT values[4]</lang>
PRINT values[4]</syntaxhighlight>


{{out}}
{{out}}
Line 319: Line 723:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
Uses the supplied SORTLIB library.
Uses the supplied SORTLIB library.
<lang bbcbasic> INSTALL @lib$+"SORTLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
sort% = FN_sortinit(0,0)
sort% = FN_sortinit(0,0)
Line 331: Line 735:
PRINT ; array(i%) ", ";
PRINT ; array(i%) ", ";
NEXT
NEXT
PRINT ; array(i%)</lang>
PRINT ; array(i%)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
1, 2, 3, 4, 5, 6, 7, 8, 9
1, 2, 3, 4, 5, 6, 7, 8, 9
</pre>
</pre>

=={{header|Beads}}==
<syntaxhighlight lang="beads">beads 1 program 'Sort an integer array'
calc main_init
var arr = [4, 1, 2, -1, 3, 0, 2]
var newarr : array of num
loop across:arr sort:val count:c val:v
newarr[c] = v</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
{{works with|befungee}}
{{works with|befungee}}
Elements of the array are read from standard input, preceded by their quantity. The algorithm uses counting sort and allows numbers between 1 and 60, inclusive.
Elements of the array are read from standard input, preceded by their quantity. The algorithm uses counting sort and allows numbers between 1 and 60, inclusive.
<syntaxhighlight lang="befunge">v
<lang Befunge>v
> 543** > :#v_ $&> :#v_ 1 > :0g > :#v_ $ 1+: 543** `! #v_ 25*,@
> 543** > :#v_ $&> :#v_ 1 > :0g > :#v_ $ 1+: 543** `! #v_ 25*,@
^-1p0\0:< ^-1 p0\+1 g0:&< ^-1\.:\<
^-1p0\0:< ^-1 p0\+1 g0:&< ^-1\.:\<
^ <</lang>
^ <</syntaxhighlight>

=={{header|BQN}}==
<syntaxhighlight lang="bqn">∧ [4, 1, 2, ¯9, ¯5, 3, 6, 9, ¯2]</syntaxhighlight>
{{out}}
<pre>⟨ ¯9 ¯5 ¯2 1 2 3 4 6 9 ⟩</pre>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Line 357: Line 774:
{!} 21</pre>
{!} 21</pre>
To complete the task need to unfold the terms with a numerical factor >1:
To complete the task need to unfold the terms with a numerical factor >1:
<lang bracmat>{sort takes a list of space-separated integers}
<syntaxhighlight lang="bracmat">{sort takes a list of space-separated integers}
(sort=
(sort=
sum elem sorted n
sum elem sorted n
Line 373: Line 790:
& !sorted);
& !sorted);
out$sort$(9 -2 1 2 8 0 1 2);</lang>
out$sort$(9 -2 1 2 8 0 1 2);</syntaxhighlight>
{{out}}
Output:
<pre>-2 0 1 1 2 2 8 9</pre>
<pre>-2 0 1 1 2 2 8 9</pre>
This solution becomes very ineffective for long lists. To add a single term to an already sorted sum of N terms requires on average N/2 steps. It is much more efficient to merge two already sorted sums of about equal length.
This solution becomes very ineffective for long lists. To add a single term to an already sorted sum of N terms requires on average N/2 steps. It is much more efficient to merge two already sorted sums of about equal length.
Line 380: Line 797:


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>{1 3 2 5 4}><</lang>
<syntaxhighlight lang="burlesque">{1 3 2 5 4}><</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdlib.h> /* qsort() */
<syntaxhighlight lang="c">#include <stdlib.h> /* qsort() */
#include <stdio.h> /* printf() */
#include <stdio.h> /* printf() */


Line 399: Line 816:
nums[0], nums[1], nums[2], nums[3], nums[4]);
nums[0], nums[1], nums[2], nums[3], nums[4]);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


''Caution:'' An older version of <tt>intcmp()</tt> did <tt>return *a - *b</tt>. This is only correct when the subtraction does not overflow. Suppose that <tt>*a = 2000000000</tt> and <tt>*b = -2000000000</tt> on a machine with 32-bit <tt>int</tt>. The subtraction <tt>*a - *b</tt> would overflow to <tt>-294967296</tt>, and <tt>intcmp()</tt> would believe <tt>*a < *b</tt>, but the correct answer is <tt>*a > *b</tt>.
''Caution:'' An older version of <tt>intcmp()</tt> did <tt>return *a - *b</tt>. This is only correct when the subtraction does not overflow. Suppose that <tt>*a = 2000000000</tt> and <tt>*b = -2000000000</tt> on a machine with 32-bit <tt>int</tt>. The subtraction <tt>*a - *b</tt> would overflow to <tt>-294967296</tt>, and <tt>intcmp()</tt> would believe <tt>*a < *b</tt>, but the correct answer is <tt>*a > *b</tt>.
Line 405: Line 822:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 413: Line 830:
Array.Sort(unsorted);
Array.Sort(unsorted);
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 419: Line 836:


===Simple Array===
===Simple Array===
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>


int main()
int main()
Line 426: Line 843:
std::sort(nums, nums+sizeof(nums)/sizeof(int));
std::sort(nums, nums+sizeof(nums)/sizeof(int));
return 0;
return 0;
}</lang>
}</syntaxhighlight>


===<tt>std::vector</tt>===
===<tt>std::vector</tt>===
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <vector>
#include <vector>


Line 442: Line 859:
std::sort(nums.begin(), nums.end());
std::sort(nums.begin(), nums.end());
return 0;
return 0;
}</lang>
}</syntaxhighlight>


===<tt>std::list</tt>===
===<tt>std::list</tt>===
<lang cpp>#include <list>
<syntaxhighlight lang="cpp">#include <list>


int main()
int main()
Line 457: Line 874:
nums.sort();
nums.sort();
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clean}}==
=={{header|Clean}}==
We use list and array comprehensions to convert an array to and from a list in order to use the built-in <tt>sort</tt> on lists.
We use list and array comprehensions to convert an array to and from a list in order to use the built-in <tt>sort</tt> on lists.
<lang clean>import StdEnv
<syntaxhighlight lang="clean">import StdEnv


sortArray :: (a e) -> a e | Array a e & Ord e
sortArray :: (a e) -> a e | Array a e & Ord e
Line 467: Line 884:


Start :: {#Int}
Start :: {#Int}
Start = sortArray {2, 4, 3, 1, 2}</lang>
Start = sortArray {2, 4, 3, 1, 2}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(sort [5 4 3 2 1]) ; sort can also take a comparator function
<syntaxhighlight lang="clojure">(sort [5 4 3 2 1]) ; sort can also take a comparator function
(1 2 3 4 5)</lang>
(1 2 3 4 5)</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|Visual COBOL}}
{{works with|Visual COBOL}}
<lang cobol> PROGRAM-ID. sort-ints.
<syntaxhighlight lang="cobol"> PROGRAM-ID. sort-ints.
DATA DIVISION.
DATA DIVISION.
Line 496: Line 913:
END-PERFORM
END-PERFORM
DISPLAY SPACE
DISPLAY SPACE
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
In Common Lisp, the ''sort'' function takes a predicate that is used as the comparator. This parameter can be any two-argument function. To sort a sequence (list or array) of integers, call ''sort'' with the < operator as the predicate:
In Common Lisp, the ''sort'' function takes a predicate that is used as the comparator. This parameter can be any two-argument function. To sort a sequence (list or array) of integers, call ''sort'' with the < operator as the predicate:
<lang lisp>CL-USER> (sort #(9 -2 1 2 8 0 1 2) #'<)
<syntaxhighlight lang="lisp">CL-USER> (sort #(9 -2 1 2 8 0 1 2) #'<)
#(-2 0 1 1 2 2 8 9)</lang>
#(-2 0 1 1 2 2 8 9)</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
Example demonstrating the support for copy sort and in-place sort (like Ruby)
Example demonstrating the support for copy sort and in-place sort (like Ruby)
<syntaxhighlight lang="ruby">
<lang Ruby>
a = [5, 4, 3, 2, 1]
a = [5, 4, 3, 2, 1]
puts a.sort
puts a.sort
Line 516: Line 933:
puts a
puts a
# => [1, 2, 3, 4, 5]
# => [1, 2, 3, 4, 5]
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.algorithm;


void main() {
void main() {
Line 525: Line 942:
data.sort(); // in-place
data.sort(); // in-place
assert(data == [1, 2, 2, 3, 4]);
assert(data == [1, 2, 2, 3, 4]);
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>uses Types, Generics.Collections;
<syntaxhighlight lang="delphi">uses Types, Generics.Collections;


var
var
Line 535: Line 952:
a := TIntegerDynArray.Create(5, 4, 3, 2, 1);
a := TIntegerDynArray.Create(5, 4, 3, 2, 1);
TArray.Sort<Integer>(a);
TArray.Sort<Integer>(a);
end;</lang>
end;</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
<lang Delphi>var a : array of Integer := [5, 4, 3, 2, 1];
<syntaxhighlight lang="delphi">var a : array of Integer := [5, 4, 3, 2, 1];
a.Sort; // ascending natural sort
a.Sort; // ascending natural sort
PrintLn(a.Map(IntToStr).Join(',')); // 1,2,3,4,5</lang>
PrintLn(a.Map(IntToStr).Join(',')); // 1,2,3,4,5</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>!. sort [ 5 4 3 2 1 ]</lang>
<syntaxhighlight lang="dejavu">!. sort [ 5 4 3 2 1 ]</syntaxhighlight>
{{out}}
{{out}}
<pre>[ 1 2 3 4 5 ]</pre>
<pre>[ 1 2 3 4 5 ]</pre>


=={{header|E}}==
=={{header|E}}==
<lang e>[2,4,3,1,2].sort()</lang>
<syntaxhighlight lang="e">[2,4,3,1,2].sort()</syntaxhighlight>


=={{header|EGL}}==
=={{header|EGL}}==
{{works with|EDT}}
{{works with|EDT}}
The following works in EDT with Rich UI and stand-alone programs.
The following works in EDT with Rich UI and stand-alone programs.
<lang EGL>program SortExample
<syntaxhighlight lang="egl">program SortExample


function main()
function main()
Line 568: Line 985:
end
end
end</lang>
end</syntaxhighlight>
{{works with|RBD}}
{{works with|RBD}}
The following works in RBD but only with Rich UI programs.
The following works in RBD but only with Rich UI programs.
<lang EGL>test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0];
<syntaxhighlight lang="egl">test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0];
RUILib.sort(test1, sortFunction);
RUILib.sort(test1, sortFunction);


Line 577: Line 994:
function sortFunction(a any in, b any in) returns (int)
function sortFunction(a any in, b any in) returns (int)
return ((a as int) - (b as int));
return ((a as int) - (b as int));
end</lang>
end</syntaxhighlight>

=={{header|Eiffel}}==

[https://github.com/ljr1981/rosettacode_answers/blob/main/testing/rc_array_sort/rc_array_sort_test_set.e Full example code]

Using a SORTED_TWO_WAY_LIST means that the contents of the list will be sorted ascending automatically.
The list can be easily sorted in reverse. There is a call for `sort' to manually initiate sorting.

<syntaxhighlight lang="eiffel">
local
l_array: SORTED_TWO_WAY_LIST [INTEGER]
do
create l_array.make_from_iterable (<<9,8,7,6,5,4,3,2,1,0>>)
end
</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
Line 589: Line 1,021:
console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable())
console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable())
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>list = [2, 4, 3, 1, 2]
<syntaxhighlight lang="elixir">list = [2, 4, 3, 1, 2]
IO.inspect Enum.sort(list)
IO.inspect Enum.sort(list)
IO.inspect Enum.sort(list, &(&1>&2))</lang>
IO.inspect Enum.sort(list, &(&1>&2))</syntaxhighlight>


{{out}}
{{out}}
Line 603: Line 1,035:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>List = [2, 4, 3, 1, 2].
<syntaxhighlight lang="erlang">List = [2, 4, 3, 1, 2].
SortedList = lists:sort(List).</lang>
SortedList = lists:sort(List).</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>include sort.e
<syntaxhighlight lang="euphoria">include sort.e
print(1,sort({20, 7, 65, 10, 3, 0, 8, -60}))</lang>
print(1,sort({20, 7, 65, 10, 3, 0, 8, -60}))</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>// sorting an array in place
<syntaxhighlight lang="fsharp">// sorting an array in place
let nums = [| 2; 4; 3; 1; 2 |]
let nums = [| 2; 4; 3; 1; 2 |]
Array.sortInPlace nums
Array.sortInPlace nums
Line 617: Line 1,049:
// create a sorted copy of a list
// create a sorted copy of a list
let nums2 = [2; 4; 3; 1; 2]
let nums2 = [2; 4; 3; 1; 2]
let sorted = List.sort nums2</lang>
let sorted = List.sort nums2</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>{ 1 4 9 2 3 0 5 } natural-sort .</lang>
<syntaxhighlight lang="factor">{ 1 4 9 2 3 0 5 } natural-sort .</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 638: Line 1,070:
{{works with|Win32Forth|4.2}}
{{works with|Win32Forth|4.2}}
===Win32Forth===
===Win32Forth===
<lang forth>create test-data 2 , 4 , 3 , 1 , 2 ,
<syntaxhighlight lang="forth">create test-data 2 , 4 , 3 , 1 , 2 ,
test-data 5 cell-sort
test-data 5 cell-sort
</syntaxhighlight>
</lang>
===ANS/ISO Forth===
===ANS/ISO Forth===
{{works with|GForth}}
{{works with|GForth}}
Line 646: Line 1,078:


Standard Forth does not have a library sort
Standard Forth does not have a library sort
<lang forth>100000 CONSTANT SIZE
<syntaxhighlight lang="forth">100000 CONSTANT SIZE


CREATE MYARRAY SIZE CELLS ALLOT
CREATE MYARRAY SIZE CELLS ALLOT
Line 688: Line 1,120:
DUP 2 < IF 2DROP EXIT THEN 1- CELLS OVER + QSORT ;</LANG>
DUP 2 < IF 2DROP EXIT THEN 1- CELLS OVER + QSORT ;</LANG>
Test at the console
Test at the console
<lang forth>FILLIT ok
<syntaxhighlight lang="forth">FILLIT ok
MYARRAY SIZE QUICKSORT ok</lang>
MYARRAY SIZE QUICKSORT ok</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Silverfrost FTN95}}
{{works with|Silverfrost FTN95}}
<lang fortran>CALL ISORT@(b, a, n)
<syntaxhighlight lang="fortran">CALL ISORT@(b, a, n)
! n = number of elements
! n = number of elements
! a = array to be sorted
! a = array to be sorted
! b = array of indices of a. b(1) 'points' to the minimum value etc.</lang>
! b = array of indices of a. b(1) 'points' to the minimum value etc.</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Qsort is not buildin, but include in the compiler package.
Qsort is not buildin, but include in the compiler package.
<lang freebasic>' version 11-03-2016
<syntaxhighlight lang="freebasic">' version 11-03-2016
' compile with: fbc -s console
' compile with: fbc -s console


Line 757: Line 1,189:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>unsorted array
<pre>unsorted array
Line 767: Line 1,199:
=={{header|Frink}}==
=={{header|Frink}}==
The following sorts an array in-place.
The following sorts an array in-place.
<lang frink>a = [5, 2, 4, 1, 6, 7, 9, 3, 8, 0]
<syntaxhighlight lang="frink">a = [5, 2, 4, 1, 6, 7, 9, 3, 8, 0]
sort[a]</lang>
sort[a]</syntaxhighlight>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>nums = [5, 2, 78, 2, 578, -42]
<syntaxhighlight lang="funl">nums = [5, 2, 78, 2, 578, -42]
println( sort(nums) ) // sort in ascending order
println( sort(nums) ) // sort in ascending order
println( nums.sortWith((>)) ) // sort in descending order</lang>
println( nums.sortWith((>)) ) // sort in descending order</syntaxhighlight>


{{out}}
{{out}}
Line 781: Line 1,213:
[578, 78, 5, 2, 2, -42]
[578, 78, 5, 2, 2, -42]
</pre>
</pre>

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
window 1, @"Sort an integer array"

void local fn DoIt
CFArrayRef array = @[@13,@71,@42,@8,@5,@27]
array = fn ArraySortedArrayUsingSelector( array, @"compare:" )
print fn ArrayComponentsJoinedByString( array, @", " )
end fn

fn DoIt

HandleEvents
</syntaxhighlight>
{{out}}
<pre>
5, 8, 13, 27, 42, 71
</pre>

=={{header|Fōrmulæ}}==

{{FormulaeEntry|page=https://formulae.org/?script=examples/Sort_an_integer_array}}

'''Solution'''

[[File:Fōrmulæ - Sort an integer array 01.png]]

[[File:Fōrmulæ - Sort an integer array 02.png]]


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=1f1d244aa95c329eb87cb538f0d5fc4a Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=1f1d244aa95c329eb87cb538f0d5fc4a Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Dim iTemp As Integer
Line 795: Line 1,256:
Print Left(sOutput, -2)
Print Left(sOutput, -2)


End</lang>
End</syntaxhighlight>


Output:
Output:
Line 803: Line 1,264:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>a := [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ];
<syntaxhighlight lang="gap">a := [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ];
# Make a copy (with "b := a;", b and a would point to the same list)
# Make a copy (with "b := a;", b and a would point to the same list)
b := ShallowCopy(a);
b := ShallowCopy(a);
Line 816: Line 1,277:
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
b;
b;
# [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ]</lang>
# [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main
import "fmt"
import "fmt"
import "sort"
import "sort"
Line 827: Line 1,288:
sort.Ints(nums)
sort.Ints(nums)
fmt.Println(nums)
fmt.Println(nums)
}</lang>
}</syntaxhighlight>


=={{header|Golfscript}}==
=={{header|Golfscript}}==
<lang golfscript>[2 4 3 1 2]$</lang>
<syntaxhighlight lang="golfscript">[2 4 3 1 2]$</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>println ([2,4,0,3,1,2,-12].sort())</lang>
<syntaxhighlight lang="groovy">println ([2,4,0,3,1,2,-12].sort())</syntaxhighlight>


Output:
Output:
Line 841: Line 1,302:
{{works with|GHC|GHCi|6.6}}
{{works with|GHC|GHCi|6.6}}
<lang haskell>nums = [2,4,3,1,2] :: [Int]
<syntaxhighlight lang="haskell">nums = [2,4,3,1,2] :: [Int]
sorted = List.sort nums</lang>
sorted = List.sort nums</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>DIMENSION array(100)
<syntaxhighlight lang="hicest">DIMENSION array(100)


array = INT( RAN(100) )
array = INT( RAN(100) )
SORT(Vector=array, Sorted=array) </lang>
SORT(Vector=array, Sorted=array) </syntaxhighlight>


=={{header|Huginn}}==
=={{header|Huginn}}==
<lang huginn>main() {
<syntaxhighlight lang="huginn">main() {
nums = [2, 4, 3, 1, 2];
nums = [2, 4, 3, 1, 2];
nums.sort();
nums.sort();
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 860: Line 1,321:


In the example below, L will remain an unsorted list and S will be sorted.
In the example below, L will remain an unsorted list and S will be sorted.
<lang Icon>S := sort(L:= [63, 92, 51, 92, 39, 15, 43, 89, 36, 69]) # will sort a list</lang>
<syntaxhighlight lang="icon">S := sort(L:= [63, 92, 51, 92, 39, 15, 43, 89, 36, 69]) # will sort a list</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
<lang idl>result = array[sort(array)]</lang>
<syntaxhighlight lang="idl">result = array[sort(array)]</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
<lang inform7>let L be {5, 4, 7, 1, 18};
<syntaxhighlight lang="inform7">let L be {5, 4, 7, 1, 18};
sort L;</lang>
sort L;</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang lua>mums := list(2,4,3,1,2)
<syntaxhighlight lang="lua">mums := list(2,4,3,1,2)
sorted := nums sort # returns a new sorted array. 'nums' is unchanged
sorted := nums sort # returns a new sorted array. 'nums' is unchanged
nums sortInPlace # sort 'nums' "in-place"</lang>
nums sortInPlace # sort 'nums' "in-place"</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>/:~</lang>
<syntaxhighlight lang="j">/:~</syntaxhighlight>
The verb<tt> /:~ </tt>sorts <i>anything</i> that J can represent. For example:
The verb<tt> /:~ </tt>sorts <i>anything</i> that J can represent. For example:


<lang j> ] a=: 10 ?@$ 100 NB. random vector
<syntaxhighlight lang="j"> ] a=: 10 ?@$ 100 NB. random vector
63 92 51 92 39 15 43 89 36 69
63 92 51 92 39 15 43 89 36 69
/:~ a
/:~ a
15 36 39 43 51 63 69 89 92 92</lang>
15 36 39 43 51 63 69 89 92 92</syntaxhighlight>
Arrays of any rank are treated as lists of component arrays. Thus <tt>/:~</tt> sorts not only atoms within a list, but whole lists within a table, tables within a three-axis array, and so on. The level of structure at which sorting occurs may also be specified, so that <tt>/:~"1</tt> sorts the atoms within the finest-grained list within the array, regardless of the overall rank of the array. See the [https://code.jsoftware.com/wiki/Essays/The_TAO_of_J Total Array Ordering essay] on the JWiki for more details.
Arrays of any rank are treated as lists of component arrays. Thus <tt>/:~</tt> sorts not only atoms within a list, but whole lists within a table, tables within a three-axis array, and so on. The level of structure at which sorting occurs may also be specified, so that <tt>/:~"1</tt> sorts the atoms within the finest-grained list within the array, regardless of the overall rank of the array. See the [[j:Essays/The_TAO_of_J|Total Array Ordering essay]] on the JWiki for more details.


This code also applies to any data type.
This code also applies to any data type.
Line 888: Line 1,349:
=={{header|Java}}==
=={{header|Java}}==
===Array===
===Array===
<lang java>import java.util.Arrays;
<syntaxhighlight lang="java">import java.util.Arrays;


public class Example {
public class Example {
Line 896: Line 1,357:
Arrays.sort(nums);
Arrays.sort(nums);
}
}
}</lang>
}</syntaxhighlight>


===List===
===List===
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.util.Arrays;
<syntaxhighlight lang="java5">import java.util.Arrays;
import java.util.Collections;
import java.util.Collections;
import java.util.List;
import java.util.List;
Line 910: Line 1,371:
Collections.sort(nums);
Collections.sort(nums);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 917: Line 1,378:
JavaScript sorts lexically by default, so "10000" comes before "2". To sort numerically, a custom comparator is used.
JavaScript sorts lexically by default, so "10000" comes before "2". To sort numerically, a custom comparator is used.


<lang javascript>function int_arr(a, b) {
<syntaxhighlight lang="javascript">function int_arr(a, b) {
return a - b;
return a - b;
}
}
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
numbers.sort(int_arr);
numbers.sort(int_arr);
document.write(numbers);</lang>
document.write(numbers);</syntaxhighlight>

=={{header|Jinja}}==
<syntaxhighlight lang="jinja">
from jinja2 import Template
print(Template("{{ [53, 17, 42, 61, 35] | sort }}").render())
</syntaxhighlight>
Descending order:
<syntaxhighlight lang="jinja">
from jinja2 import Template
print(Template("{{ [53, 17, 42, 61, 35] | sort(reverse=true) }}").render())
</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
jq's builtin <code>sort</code> filter sorts the elements of an array in ascending order:
jq's builtin <code>sort</code> filter sorts the elements of an array in ascending order:
<lang jq>[2,1,3] | sort # => [1,2,3]</lang>
<syntaxhighlight lang="jq">[2,1,3] | sort # => [1,2,3]</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Julia has both out-of-place (<code>sort</code>) and in-place (<code>sort!</code>) sorting functions in its standard-library:
Julia has both out-of-place (<code>sort</code>) and in-place (<code>sort!</code>) sorting functions in its standard-library:
<lang julia>julia> a = [4,2,3,1]
<syntaxhighlight lang="julia">julia> a = [4,2,3,1]
4-element Int32 Array:
4-element Int32 Array:
4
4
Line 962: Line 1,434:
2
2
3
3
4</lang>
4</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
<lang k> num: -10?10 / Integers from 0 to 9 in random order
<syntaxhighlight lang="k"> num: -10?10 / Integers from 0 to 9 in random order
5 9 4 2 0 3 6 1 8 7
5 9 4 2 0 3 6 1 8 7


srt: {x@<x} / Generalized sort ascending
srt: {x@<x} / Generalized sort ascending
srt num
srt num
0 1 2 3 4 5 6 7 8 9</lang>
0 1 2 3 4 5 6 7 8 9</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 979: Line 1,451:
ints.sort()
ints.sort()
println(ints.joinToString(prefix = "[", postfix = "]"))
println(ints.joinToString(prefix = "[", postfix = "]"))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 987: Line 1,459:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
1) sorting digits in a number returns a new number of ordered digits
1) sorting digits in a number returns a new number of ordered digits
{W.sort < 51324}
{W.sort < 51324}
Line 999: Line 1,471:
{A.sort! < {A.new 51 111 33 2 41}}
{A.sort! < {A.new 51 111 33 2 41}}
-> [2,33,41,51,111]
-> [2,33,41,51,111]
</syntaxhighlight>
</lang>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(array) = array(5,20,3,2,6,1,4)
<syntaxhighlight lang="lasso">local(array) = array(5,20,3,2,6,1,4)
#array->sort
#array->sort
#array // 1, 2, 3, 4, 5, 6, 20
#array // 1, 2, 3, 4, 5, 6, 20
Line 1,008: Line 1,480:
// Reverse the sort order
// Reverse the sort order
#array->sort(false)
#array->sort(false)
#array // 20, 6, 5, 4, 3, 2, 1</lang>
#array // 20, 6, 5, 4, 3, 2, 1</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
LB has an array-sort command. Parameters are arrayname, start term, finish term.
LB has an array-sort command. Parameters are arrayname, start term, finish term.
<lang lb>N =20
<syntaxhighlight lang="lb">N =20
dim IntArray( N)
dim IntArray( N)


Line 1,027: Line 1,499:
for i =1 to N
for i =1 to N
print IntArray( i)
print IntArray( i)
next i</lang>
next i</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>l = [7, 4, 23]
<syntaxhighlight lang="lingo">l = [7, 4, 23]
l.sort()
l.sort()
put l
put l
-- [4, 7, 23]</lang>
-- [4, 7, 23]</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
LiveCode can sort lines or items natively. The delimiter for items can be set to any single character, but defaults to comma.
LiveCode can sort lines or items natively. The delimiter for items can be set to any single character, but defaults to comma.
<lang LiveCode>put "3,2,5,4,1" into X
<syntaxhighlight lang="livecode">put "3,2,5,4,1" into X
sort items of X numeric
sort items of X numeric
put X
put X
-- outputs "1,2,3,4,5"</lang>
-- outputs "1,2,3,4,5"</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>t = {4, 5, 2}
<syntaxhighlight lang="lua">t = {4, 5, 2}
table.sort(t)
table.sort(t)
print(unpack(t))</lang>
print(unpack(t))</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>sort([5,7,8,3,6,1]);
<syntaxhighlight lang="maple">sort([5,7,8,3,6,1]);
sort(Array([5,7,8,3,6,1]))</lang>
sort(Array([5,7,8,3,6,1]))</syntaxhighlight>


=={{header|Mathematica}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang mathematica>numbers = Sort[{2,4,3,1,2}]</lang>
<syntaxhighlight lang="mathematica">numbers=Sort[{2,4,3,1,2}]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang Matlab>a = [4,3,7,-2,9,1]; b = sort(a) % b contains elements of a in ascending order
<syntaxhighlight lang="matlab">a = [4,3,7,-2,9,1]; b = sort(a) % b contains elements of a in ascending order
[b,idx] = sort(a) % b contains a(idx)</lang>
[b,idx] = sort(a) % b contains a(idx)</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>sort([9, 4, 3, 7, 6, 1, 10, 2, 8, 5]);</lang>
<syntaxhighlight lang="maxima">sort([9, 4, 3, 7, 6, 1, 10, 2, 8, 5]);</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>arr = #(5, 4, 3, 2, 1)
<syntaxhighlight lang="maxscript">arr = #(5, 4, 3, 2, 1)
arr = sort arr</lang>
arr = sort arr</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang>:- module sort_int_list.
<syntaxhighlight lang="text">:- module sort_int_list.
:- interface.
:- interface.
:- import_module io.
:- import_module io.
Line 1,079: Line 1,551:
list.sort(Nums, Sorted),
list.sort(Nums, Sorted),
io.write(Sorted, !IO),
io.write(Sorted, !IO),
io.nl(!IO).</lang>
io.nl(!IO).</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(5 2 1 3 4) '> sort print</lang>
<syntaxhighlight lang="min">(5 2 1 3 4) '> sort print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,091: Line 1,563:
=={{header|Modula-3}}==
=={{header|Modula-3}}==
Modula-3 provides a generic <tt>ArraySort</tt> module, as well as an instance of that module for integers called <tt>IntArraySort</tt>.
Modula-3 provides a generic <tt>ArraySort</tt> module, as well as an instance of that module for integers called <tt>IntArraySort</tt>.
<lang modula3>MODULE ArraySort EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE ArraySort EXPORTS Main;


IMPORT IntArraySort;
IMPORT IntArraySort;
Line 1,099: Line 1,571:
BEGIN
BEGIN
IntArraySort.Sort(arr);
IntArraySort.Sort(arr);
END ArraySort.</lang>
END ArraySort.</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>SORTARRAY(X,SEP)
<syntaxhighlight lang="mumps">SORTARRAY(X,SEP)
;X is the list of items to sort
;X is the list of items to sort
;X1 is the temporary array
;X1 is the temporary array
Line 1,113: Line 1,585:
SET I="" FOR SET I=$O(X1(I)) Q:I="" SET Y=$SELECT($L(Y)=0:I,1:Y_SEP_I)
SET I="" FOR SET I=$O(X1(I)) Q:I="" SET Y=$SELECT($L(Y)=0:I,1:Y_SEP_I)
KILL I,X1
KILL I,X1
QUIT Y</lang>
QUIT Y</syntaxhighlight>
Output:<pre>USER>W $$SORTARRAY^ROSETTA("3,5,1,99,27,16,0,-1",",")
Output:<pre>USER>W $$SORTARRAY^ROSETTA("3,5,1,99,27,16,0,-1",",")
-1,0,1,3,5,16,27,99
-1,0,1,3,5,16,27,99
Line 1,120: Line 1,592:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
'sort' in the Nanoquery standard library has a Quicksort function.
'sort' in the Nanoquery standard library has a Quicksort function.
<lang Nanoquery>% import sort
<syntaxhighlight lang="nanoquery">% import sort
% println sort({2,4,3,1,2})
% println sort({2,4,3,1,2})
[1, 2, 2, 3, 4]</lang>
[1, 2, 2, 3, 4]</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
<doc><h2>Sort integer array, in Neko</h2>
<doc><h2>Sort integer array, in Neko</h2>
<p>Array sort function modified from Haxe codegen with -D neko-source</p>
<p>Array sort function modified from Haxe codegen with -D neko-source</p>
Line 1,164: Line 1,636:


/* Also returns the sorted array for chaining */
/* Also returns the sorted array for chaining */
$print(sort($array(3,1,4,1,5,9,2,6,5,3,5,8)), "\n")</lang>
$print(sort($array(3,1,4,1,5,9,2,6,5,3,5,8)), "\n")</syntaxhighlight>


{{out}}
{{out}}
Line 1,174: Line 1,646:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System.Console;
<syntaxhighlight lang="nemerle">using System.Console;


module IntSort
module IntSort
Line 1,186: Line 1,658:
WriteLine(sorted);
WriteLine(sorted);
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>[1, 5, 3, 7, 2, 8, 3, 9]
<pre>[1, 5, 3, 7, 2, 8, 3, 9]
Line 1,192: Line 1,664:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
options replace format comments java crossref savelog symbols binary


Line 1,213: Line 1,685:
say sorted.strip('t')
say sorted.strip('t')


return</lang>
return</syntaxhighlight>


'''Output'''
'''Output'''
Line 1,223: Line 1,695:
NetRexx reimplementations of the [[#REXX|Rexx]] samples from below:
NetRexx reimplementations of the [[#REXX|Rexx]] samples from below:


<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols
options replace format comments java crossref savelog symbols


Line 1,294: Line 1,766:
say
say


return</lang>
return</syntaxhighlight>


'''Output'''
'''Output'''
Line 1,345: Line 1,817:
</pre>
</pre>


<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols
options replace format comments java crossref savelog symbols


Line 1,398: Line 1,870:
end
end


return</lang>
return</syntaxhighlight>


'''Output'''
'''Output'''
Line 1,407: Line 1,879:


=={{header|Nial}}==
=={{header|Nial}}==
<lang nial>sort >= 9 6 8 7 1 10
<syntaxhighlight lang="nial">sort >= 9 6 8 7 1 10
= 10 9 8 7 6 1</lang>
= 10 9 8 7 6 1</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import algorithm
<syntaxhighlight lang="nim">import algorithm
var a: array[0..8,int] = [2,3,5,8,4,1,6,9,7]
var a: array[0..8, int] = [2, 3, 5, 8, 4, 1, 6, 9, 7]
a.sort(system.cmp[int], Ascending)
a.sort(Ascending)
for x in a:
for x in a:
echo(x)</lang>
echo x</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,430: Line 1,902:
=={{header|Niue}}==
=={{header|Niue}}==
'''Library'''
'''Library'''
<lang Niue>2 6 1 0 3 8 sort .s
<syntaxhighlight lang="niue">2 6 1 0 3 8 sort .s
0 1 2 3 6 8</lang>
0 1 2 3 6 8</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class Sort {
class Sort {
function : Main(args : System.String[]) ~ Nil {
function : Main(args : System.String[]) ~ Nil {
Line 1,441: Line 1,913:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>NSArray *nums = @[@2, @4, @3, @1, @2];
<syntaxhighlight lang="objc">NSArray *nums = @[@2, @4, @3, @1, @2];
NSArray *sorted = [nums sortedArrayUsingSelector:@selector(compare:)];</lang>
NSArray *sorted = [nums sortedArrayUsingSelector:@selector(compare:)];</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
===Array===
===Array===
<lang ocaml>let nums = [|2; 4; 3; 1; 2|]
<syntaxhighlight lang="ocaml">let nums = [|2; 4; 3; 1; 2|]
Array.sort compare nums</lang>
Array.sort compare nums</syntaxhighlight>


===List===
===List===
<lang ocaml>let nums = [2; 4; 3; 1; 2]
<syntaxhighlight lang="ocaml">let nums = [2; 4; 3; 1; 2]
let sorted = List.sort compare nums</lang>
let sorted = List.sort compare nums</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
Line 1,460: Line 1,932:
The variable <tt>v</tt> can be a vector or a matrix (columns will be sorted).
The variable <tt>v</tt> can be a vector or a matrix (columns will be sorted).


<lang octave>sortedv = sort(v);</lang>
<syntaxhighlight lang="octave">sortedv = sort(v);</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>[ 8, 2, 5, 9, 1, 3, 6, 7, 4 ] sort</lang>
<syntaxhighlight lang="oforth">[ 8, 2, 5, 9, 1, 3, 6, 7, 4 ] sort</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang rexx>a = .array~of(4, 1, 6, -2, 99, -12)
<syntaxhighlight lang="rexx">a = .array~of(4, 1, 6, -2, 99, -12)
say "The sorted numbers are"
say "The sorted numbers are"
say a~sortWith(.numericComparator~new)~makeString</lang>
say a~sortWith(.numericComparator~new)~makeString</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,483: Line 1,955:
=={{header|Order}}==
=={{header|Order}}==
Passing the less-than operator to the built-in sequence (i.e. list) sort function:
Passing the less-than operator to the built-in sequence (i.e. list) sort function:
<lang c>#include <order/interpreter.h>
<syntaxhighlight lang="c">#include <order/interpreter.h>


ORDER_PP( 8seq_sort(8less, 8seq(2, 4, 3, 1, 2)) )</lang>
ORDER_PP( 8seq_sort(8less, 8seq(2, 4, 3, 1, 2)) )</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
Nums = [2 4 3 1 2]
Nums = [2 4 3 1 2]
Sorted = {List.sort Nums Value.'<'}
Sorted = {List.sort Nums Value.'<'}
in
in
{Show Sorted}</lang>
{Show Sorted}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>vecsort(v)</lang>
<syntaxhighlight lang="parigp">vecsort(v)</syntaxhighlight>


=={{header|Peloton}}==
=={{header|Peloton}}==
Sorting a list of numbers as strings and as numbers (from the manual.)
Sorting a list of numbers as strings and as numbers (from the manual.)
<lang sgml>Construct a list of numbers
<syntaxhighlight lang="sgml">Construct a list of numbers
<@ LETCNSLSTLIT>L|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@>
<@ LETCNSLSTLIT>L|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@>
Numbers sort as strings
Numbers sort as strings
Line 1,513: Line 1,985:
<@ SAYDMPLST>list</@>
<@ SAYDMPLST>list</@>
<@ ACTSRTENTLSTLIT>list|__NumericDescending</@>
<@ ACTSRTENTLSTLIT>list|__NumericDescending</@>
<@ SAYDMPLST>list</@></lang>
<@ SAYDMPLST>list</@></syntaxhighlight>


Output
Output
<lang html>Construct a list of numbers
<syntaxhighlight lang="html">Construct a list of numbers
Numbers sort as strings
Numbers sort as strings
Line 1,530: Line 2,002:
1^2^3^4^4^25^25^39^41^42^44^45^47^51^65^69^77^84^
1^2^3^4^4^25^25^39^41^42^44^45^47^51^65^69^77^84^
84^77^69^65^51^47^45^44^42^41^39^25^25^4^4^3^2^1^</lang>
84^77^69^65^51^47^45^44^42^41^39^25^25^4^4^3^2^1^</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
{{works with|Perl|5.8.6}}
{{works with|Perl|5.8.6}}
<lang perl>@nums = (2,4,3,1,2);
<syntaxhighlight lang="perl">@nums = (2,4,3,1,2);
@sorted = sort {$a <=> $b} @nums;</lang>
@sorted = sort {$a <=> $b} @nums;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang Phix>?sort({9, 10, 3, 1, 4, 5, 8, 7, 6, 2})</lang>
<!--<syntaxhighlight lang="phix">-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</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;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


( 9 10 3 1 4 5 8 7 6 2 ) sort print</lang>
( 9 10 3 1 4 5 8 7 6 2 ) sort print</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
{{works with|PHP|4.4.4 CLI}}
{{works with|PHP|4.4.4 CLI}}
<lang php><?php
<syntaxhighlight lang="php"><?php
$nums = array(2,4,3,1,2);
$nums = array(2,4,3,1,2);
sort($nums);
sort($nums);
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
The [http://software-lab.de/doc/refS.html#sort sort] function in PicoLisp
The [http://software-lab.de/doc/refS.html#sort sort] function in PicoLisp
returns already by default an ascending list (of any type, not only integers):
returns already by default an ascending list (of any type, not only integers):
<lang PicoLisp>(sort (2 4 3 1 2))
<syntaxhighlight lang="picolisp">(sort (2 4 3 1 2))
-> (1 2 2 3 4)</lang>
-> (1 2 2 3 4)</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
{{works with|IBM PL/I|7.5}}
{{works with|IBM PL/I|7.5}}
<lang pli>DCL (T(10)) FIXED BIN(31); /* scratch space of length N/2 */
<syntaxhighlight lang="pli">DCL (T(10)) FIXED BIN(31); /* scratch space of length N/2 */


MERGE: PROCEDURE (A,LA,B,LB,C);
MERGE: PROCEDURE (A,LA,B,LB,C);
Line 1,596: Line 2,071:
CALL MERGE(T,M,AMP1,N-M,A);
CALL MERGE(T,M,AMP1,N-M,A);
RETURN;
RETURN;
END MERGESORT;</lang>
END MERGESORT;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
Pop11 library function sorts lists. So we first convert array to list, then sort and finally convert back:
Pop11 library function sorts lists. So we first convert array to list, then sort and finally convert back:


<lang pop11>lvars ar = {2 4 3 1 2};
<syntaxhighlight lang="pop11">lvars ar = {2 4 3 1 2};
;;; Convert array to list.
;;; Convert array to list.
;;; destvector leaves its results and on the pop11 stack + an integer saying how many there were
;;; destvector leaves its results and on the pop11 stack + an integer saying how many there were
Line 1,611: Line 2,086:
;;; Convert list to array
;;; Convert list to array
destlist(ls);
destlist(ls);
consvector() -> ar;</lang>
consvector() -> ar;</syntaxhighlight>


The above can be abbreviated to more economical, but possibly more opaque, syntax, using pop11 as a functional language:
The above can be abbreviated to more economical, but possibly more opaque, syntax, using pop11 as a functional language:


<lang pop11>lvars ar = {2 4 3 1 2};
<syntaxhighlight lang="pop11">lvars ar = {2 4 3 1 2};
consvector(destlist(sort(conslist(destvector(ar))))) -> ar;
consvector(destlist(sort(conslist(destvector(ar))))) -> ar;
;;; print the sorted vector:
;;; print the sorted vector:
ar =>
ar =>
** {1 2 2 3 4}</lang>
** {1 2 2 3 4}</syntaxhighlight>


(The list created by conslist will be garbage-collected.)
(The list created by conslist will be garbage-collected.)
Line 1,625: Line 2,100:
Alternatively, using the datalist function, even more economically:
Alternatively, using the datalist function, even more economically:


<lang pop11>lvars ar = {2 4 3 1 2};
<syntaxhighlight lang="pop11">lvars ar = {2 4 3 1 2};
consvector(destlist(sort(datalist(ar)))) -> ar;</lang>
consvector(destlist(sort(datalist(ar)))) -> ar;</syntaxhighlight>


or in Forth-like pop11 postfix syntax:
or in Forth-like pop11 postfix syntax:


<lang pop11>lvars ar = {2 4 3 1 2};
<syntaxhighlight lang="pop11">lvars ar = {2 4 3 1 2};
ar.datalist.sort.destlist.consvector -> ar;</lang>
ar.datalist.sort.destlist.consvector -> ar;</syntaxhighlight>


=={{header|Potion}}==
=={{header|Potion}}==
<lang potion>(7, 5, 1, 2, 3, 8, 9) sort join(", ") print</lang>
<syntaxhighlight lang="potion">(7, 5, 1, 2, 3, 8, 9) sort join(", ") print</syntaxhighlight>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
PowerBASIC has several options available for sorting. At its simplest, an array (of any type) is sorted using <code>ARRAY SORT</code>:
PowerBASIC has several options available for sorting. At its simplest, an array (of any type) is sorted using <code>ARRAY SORT</code>:
<lang powerbasic>ARRAY SORT x()</lang>
<syntaxhighlight lang="powerbasic">ARRAY SORT x()</syntaxhighlight>


Options are available to limit sorting to only part of the array, collate string arrays, sort multiple arrays together, etc. (Details [http://www.powerbasic.com/support/help/pbwin/html/ARRAY_SORT_statement.htm here].)
Options are available to limit sorting to only part of the array, collate string arrays, sort multiple arrays together, etc. (Details [http://www.powerbasic.com/support/help/pbwin/html/ARRAY_SORT_statement.htm here].)


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>34,12,23,56,1,129,4,2,73 | Sort-Object</lang>
<syntaxhighlight lang="powershell">34,12,23,56,1,129,4,2,73 | Sort-Object</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 1,652: Line 2,127:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Dim numbers(20)
<syntaxhighlight lang="purebasic">Dim numbers(20)
For i = 0 To 20
For i = 0 To 20
numbers(i) = Random(1000)
numbers(i) = Random(1000)
Next
Next


SortArray(numbers(), #PB_Sort_Ascending)</lang>
SortArray(numbers(), #PB_Sort_Ascending)</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.3}}
{{works with|Python|2.3}}
<lang python>nums = [2,4,3,1,2]
<syntaxhighlight lang="python">nums = [2,4,3,1,2]
nums.sort()</lang>
nums.sort()</syntaxhighlight>


'''Note:''' The array <tt>nums</tt> is sorted in place.
'''Note:''' The array <tt>nums</tt> is sorted in place.
Line 1,670: Line 2,145:
You could also use the built-in sorted() function
You could also use the built-in sorted() function


<lang python>nums = sorted([2,4,3,1,2])</lang>
<syntaxhighlight lang="python">nums = sorted([2,4,3,1,2])</syntaxhighlight>

=={{header|Quackery}}==

As a dialogue in the Quackery shell.

<pre>/O> [] 20 times [ 10 random join ]
... dup echo cr
... sort
... echo cr
...
[ 5 2 5 0 4 5 1 5 1 1 0 3 7 2 0 9 6 1 8 7 ]
[ 0 0 0 1 1 1 1 2 2 3 4 5 5 5 5 6 7 7 8 9 ]
</pre>


=={{header|R}}==
=={{header|R}}==
<lang r>nums <- c(2,4,3,1,2)
<syntaxhighlight lang="r">nums <- c(2,4,3,1,2)
sorted <- sort(nums)</lang>
sorted <- sort(nums)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
-> (sort '(1 9 2 8 3 7 4 6 5) <)
-> (sort '(1 9 2 8 3 7 4 6 5) <)
'(1 2 3 4 5 6 7 8 9)
'(1 2 3 4 5 6 7 8 9)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,686: Line 2,174:
If <code>@a</code> contains only numbers:
If <code>@a</code> contains only numbers:


<lang perl6>my @sorted = sort @a;</lang>
<syntaxhighlight lang="raku" line>my @sorted = sort @a;</syntaxhighlight>


For an in-place sort:
For an in-place sort:


<lang perl6>@a .= sort;</lang>
<syntaxhighlight lang="raku" line>@a .= sort;</syntaxhighlight>


=={{header|Rascal}}==
=={{header|Rascal}}==
Rascal has a built-in sort function that sort the elements of a list. Additionally, one can give a LessThenOrEqual function to compare the elements (See [http://tutor.rascal-mpl.org/Courses/Rascal/Rascal.html#/Courses/Rascal/Libraries/Prelude/List/sort/sort.html documentation]).
Rascal has a built-in sort function that sort the elements of a list. Additionally, one can give a LessThenOrEqual function to compare the elements (See [http://tutor.rascal-mpl.org/Courses/Rascal/Rascal.html#/Courses/Rascal/Libraries/Prelude/List/sort/sort.html documentation]).
<lang rascal>rascal>import List;
<syntaxhighlight lang="rascal">rascal>import List;
ok
ok


Line 1,704: Line 2,192:


rascal>sort(a, bool(int a, int b){return a >= b;})
rascal>sort(a, bool(int a, int b){return a >= b;})
list[int]: [5,4,3,2,1]</lang>
list[int]: [5,4,3,2,1]</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
Sort list in place:
Sort list in place:


<lang raven>[ 2 4 3 1 2 ] sort</lang>
<syntaxhighlight lang="raven">[ 2 4 3 1 2 ] sort</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>sort [2 4 3 1 2]</lang>
<syntaxhighlight lang="rebol">sort [2 4 3 1 2]</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>>> nums: [3 2 6 4 1 9 0 5 7]
<syntaxhighlight lang="red">>> nums: [3 2 6 4 1 9 0 5 7]
== [3 2 6 4 1 9 0 5 7]
== [3 2 6 4 1 9 0 5 7]
>> sort nums
>> sort nums
== [0 1 2 3 4 5 6 7 9]</lang>
== [0 1 2 3 4 5 6 7 9]</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===sort an array===
===sort an array===
This REXX version creates an array with over a score of Euler numbers (integers), then sorts it.
This REXX version creates an array with over a score of Euler numbers (integers), then sorts it.
<lang rexx>/*REXX program sorts an array (using E─sort), in this case, the array contains integers.*/
<syntaxhighlight lang="rexx">/*REXX program sorts an array (using E─sort), in this case, the array contains integers.*/
numeric digits 30 /*enables handling larger Euler numbers*/
numeric digits 30 /*enables handling larger Euler numbers*/
@. = 0; @.1 = 1
@. = 0; @.1 = 1
Line 1,751: Line 2,239:
do j=1 for #; say _ arg(1) 'array element' right(j, w)"="right(@.j, 20)
do j=1 for #; say _ arg(1) 'array element' right(j, w)"="right(@.j, 20)
end /*j*/
end /*j*/
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default internal input:}}
{{out|output|text=&nbsp; when using the default internal input:}}
<pre>
<pre>
Line 1,805: Line 2,293:
Because it so much more efficient to sort an array, &nbsp; an array is built from the list,
Because it so much more efficient to sort an array, &nbsp; an array is built from the list,
<br>it is then sorted, &nbsp; and then the list is re-constituted.
<br>it is then sorted, &nbsp; and then the list is re-constituted.
<lang rexx>/*REXX program sorts (using E─sort) and displays a list of some interesting integers. */
<syntaxhighlight lang="rexx">/*REXX program sorts (using E─sort) and displays a list of some interesting integers. */
Bell= 1 1 2 5 15 52 203 877 4140 21147 115975 /*a few Bell " */
Bell= 1 1 2 5 15 52 203 877 4140 21147 115975 /*a few Bell " */
Bern= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617' /*" " Bernoulli " */
Bern= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617' /*" " Bernoulli " */
Line 1,830: Line 2,318:
end /*i*/
end /*i*/
end /*while h>1*/
end /*while h>1*/
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default internal inputs:}}
{{out|output|text=&nbsp; when using the default internal inputs:}}


Line 1,841: Line 2,329:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>aArray = [2,4,3,1,2]
<syntaxhighlight lang="ring">aArray = [2,4,3,1,2]
see sort(aArray)</lang>
see sort(aArray)</syntaxhighlight>


=={{header|RPL}}==
{{works with|HP|48G}}
{2 4 3 1 2} SORT
{{out}}
<pre>
1: { 1 2 2 3 4 }
</pre>
=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>nums = [2,4,3,1,2]
<syntaxhighlight lang="ruby">nums = [2,4,3,1,2]
sorted = nums.sort # returns a new sorted array. 'nums' is unchanged
sorted = nums.sort # returns a new sorted array. 'nums' is unchanged
p sorted #=> [1, 2, 2, 3, 4]
p sorted #=> [1, 2, 2, 3, 4]
Line 1,851: Line 2,346:


nums.sort! # sort 'nums' "in-place"
nums.sort! # sort 'nums' "in-place"
p nums #=> [1, 2, 2, 3, 4]</lang>
p nums #=> [1, 2, 2, 3, 4]</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Uses merge sort in place (undocumented), allocating ~2*n memory where n is a length of an array.
Uses merge sort in place (undocumented), allocating ~2*n memory where n is a length of an array.
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);


a.sort();
a.sort();
println!("{:?}", a);
println!("{:?}", a);
}</lang>
}</syntaxhighlight>

=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
main is
arr: ARRAY{INT} := |4, 6, 7, 2, 1, 0, 100, 21, 34|;
#OUT+"unsorted: " + arr + "\n";

-- sort in place:
arr.sort;

#OUT+" sorted: " + arr + "\n";
end;
end;</syntaxhighlight>

Output:
<syntaxhighlight lang="text">unsorted: {4,6,7,2,1,0,100,21,34}
sorted: {0,1,2,4,6,7,21,34,100}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
===Array===
===Array===
Scala's "default" Array is a ''mutable'' data structure, very close to Java's Array. Generally speaking, that means an "array" is not very Scala-lesque, even as mutable data structures go. It can serves a purpose, though. If array is the right data type for your need, then that is how you sort it.<lang Scala>import scala.compat.Platform
Scala's "default" Array is a ''mutable'' data structure, very close to Java's Array. Generally speaking, that means an "array" is not very Scala-lesque, even as mutable data structures go. It can serves a purpose, though. If array is the right data type for your need, then that is how you sort it.<syntaxhighlight lang="scala">import scala.compat.Platform


object Sort_an_integer_array extends App {
object Sort_an_integer_array extends App {
Line 1,879: Line 2,391:


println(s"Array in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
println(s"Array in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}</lang>
}</syntaxhighlight>
===List===
===List===
<lang Scala>println(List(5,2,78,2,578,-42).sorted)
<syntaxhighlight lang="scala">println(List(5,2,78,2,578,-42).sorted)
//--> List(-42, 2, 2, 5, 78, 578)</lang>
//--> List(-42, 2, 2, 5, 78, 578)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Guile}}
{{works with|Guile}}
Same as [[Common Lisp]]
Same as [[Common Lisp]]
<lang scheme>(sort #(9 -2 1 2 8 0 1 2) #'<)</lang>
<syntaxhighlight lang="scheme">(sort #(9 -2 1 2 8 0 1 2) #'<)</syntaxhighlight>


{{libheader|Scheme/SRFIs}}
{{libheader|Scheme/SRFIs}}
Line 1,893: Line 2,405:
Sorting is also available through SRFIs. SRFI 132 provides separate list-sort and vector-sort routines:
Sorting is also available through SRFIs. SRFI 132 provides separate list-sort and vector-sort routines:


<lang scheme>
<syntaxhighlight lang="scheme">
> (import (srfi 132))
> (import (srfi 132))
> (list-sort < '(9 -2 1 2 8 0 1 2))
> (list-sort < '(9 -2 1 2 8 0 1 2))
Line 1,900: Line 2,412:
> (vector-sort < #(9 -2 1 2 8 0 1 2))
> (vector-sort < #(9 -2 1 2 8 0 1 2))
#(-2 0 1 1 2 2 8 9)
#(-2 0 1 1 2 2 8 9)
</syntaxhighlight>
</lang>


SRFI 132 replaced the older SRFI 95, which is still found in many implementations. SRFI 95 provides a generic sort function (but note the order of the sequence and comparator!):
SRFI 132 replaced the older SRFI 95, which is still found in many implementations. SRFI 95 provides a generic sort function (but note the order of the sequence and comparator!):


<lang scheme>
<syntaxhighlight lang="scheme">
> (import (srfi 95))
> (import (srfi 95))
> (sort '(9 -2 1 2 8 0 1 2) <)
> (sort '(9 -2 1 2 8 0 1 2) <)
Line 1,910: Line 2,422:
> (sort #(9 -2 1 2 8 0 1 2) <)
> (sort #(9 -2 1 2 8 0 1 2) <)
#(-2 0 1 1 2 2 8 9)
#(-2 0 1 1 2 2 8 9)
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>var array integer: nums is [] (2, 4, 3, 1, 2);
<syntaxhighlight lang="seed7">var array integer: nums is [] (2, 4, 3, 1, 2);


nums := sort(nums);</lang>
nums := sort(nums);</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var nums = [2,4,3,1,2];
<syntaxhighlight lang="ruby">var nums = [2,4,3,1,2];
var sorted = nums.sort; # returns a new sorted array.
var sorted = nums.sort; # returns a new sorted array.
nums.sort!; # sort 'nums' "in-place"</lang>
nums.sort!; # sort 'nums' "in-place"</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate> #(7 5 2 9 0 -1) sort</lang>
<syntaxhighlight lang="slate"> #(7 5 2 9 0 -1) sort</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk> #(7 5 2 9 0 -1) asSortedCollection</lang>
<syntaxhighlight lang="smalltalk"> #(7 5 2 9 0 -1) asSortedCollection</syntaxhighlight>
or destructive:
or destructive:
<lang smalltalk> #(7 5 2 9 0 -1) sort</lang>
<syntaxhighlight lang="smalltalk"> #(7 5 2 9 0 -1) sort</syntaxhighlight>

=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "int_sort" )
@( description, "Sort an array (or list) of integers in ascending" )
@( description, "numerical order. Use a sorting facility provided by" )
@( description, "the language/library if possible." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Sort_an_integer_array" );
pragma license( unrestricted );

pragma software_model( nonstandard );
pragma restriction( no_external_commands );

procedure int_sort is
type int_array is array (1..9) of integer;
int_values : int_array := (0,1,8,2,7,3,6,4,5);
begin
arrays.heap_sort( int_values );
for i in arrays.first( int_values )..arrays.last( int_values ) loop
? int_values(i);
end loop;
end int_sort;</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>var arr = { 2, 8, 1, 4, 6, 5, 3, 7, 0, 9 };
<syntaxhighlight lang="sparkling">var arr = { 2, 8, 1, 4, 6, 5, 3, 7, 0, 9 };
sort(arr);</lang>
sort(arr);</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
Line 1,939: Line 2,476:
===Array===
===Array===
{{works with|SML/NJ}}
{{works with|SML/NJ}}
<lang sml>- val nums = Array.fromList [2, 4, 3, 1, 2];
<syntaxhighlight lang="sml">- val nums = Array.fromList [2, 4, 3, 1, 2];
val nums = [|2,4,3,1,2|] : int array
val nums = [|2,4,3,1,2|] : int array
- ArrayQSort.sort Int.compare nums;
- ArrayQSort.sort Int.compare nums;
val it = () : unit
val it = () : unit
- nums;
- nums;
val it = [|1,2,2,3,4|] : int array</lang>
val it = [|1,2,2,3,4|] : int array</syntaxhighlight>


{{works with|Moscow ML}}
{{works with|Moscow ML}}
<lang sml>- load "Arraysort";
<syntaxhighlight lang="sml">- load "Arraysort";
> val it = () : unit
> val it = () : unit
- load "Int";
- load "Int";
Line 1,956: Line 2,493:
> val it = () : unit
> val it = () : unit
- Array.foldr op:: [] nums;
- Array.foldr op:: [] nums;
> val it = [1, 2, 2, 3, 4] : int list</lang>
> val it = [1, 2, 2, 3, 4] : int list</syntaxhighlight>


===List===
===List===
{{works with|SML/NJ}}
{{works with|SML/NJ}}
<lang sml>- val nums = [2, 4, 3, 1, 2];
<syntaxhighlight lang="sml">- val nums = [2, 4, 3, 1, 2];
val nums = [2,4,3,1,2] : int list
val nums = [2,4,3,1,2] : int list
- val sorted = ListMergeSort.sort op> nums;
- val sorted = ListMergeSort.sort op> nums;
val sorted = [1,2,2,3,4] : int list</lang>
val sorted = [1,2,2,3,4] : int list</syntaxhighlight>


{{works with|Moscow ML}}
{{works with|Moscow ML}}
<lang sml>- load "Listsort";
<syntaxhighlight lang="sml">- load "Listsort";
> val it = () : unit
> val it = () : unit
- load "Int";
- load "Int";
Line 1,973: Line 2,510:
> val nums = [2, 4, 3, 1, 2] : int list
> val nums = [2, 4, 3, 1, 2] : int list
- val sorted = Listsort.sort Int.compare nums;
- val sorted = Listsort.sort Int.compare nums;
> val sorted = [1, 2, 2, 3, 4] : int list</lang>
> val sorted = [1, 2, 2, 3, 4] : int list</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
Line 1,979: Line 2,516:
See '''[https://www.stata.com/help.cgi?sort sort]''' in Stata help.
See '''[https://www.stata.com/help.cgi?sort sort]''' in Stata help.


<lang stata>. clear
<syntaxhighlight lang="stata">. clear
. matrix a=(2,9,4,7,5,3,6,1,8)'
. matrix a=(2,9,4,7,5,3,6,1,8)'
. qui svmat a
. qui svmat a
Line 1,998: Line 2,535:
8. | 8 |
8. | 8 |
9. | 9 |
9. | 9 |
+----+</lang>
+----+</syntaxhighlight>


=== Sort a macro list ===
=== Sort a macro list ===
See '''[https://www.stata.com/help.cgi?macrolists macrolists]''' in Stata help for other functions on lists stored in macros.
See '''[https://www.stata.com/help.cgi?macrolists macrolists]''' in Stata help for other functions on lists stored in macros.


<lang stata>. local a 2 9 4 7 5 3 6 1 8
<syntaxhighlight lang="stata">. local a 2 9 4 7 5 3 6 1 8
. di "`: list sort a'"
. di "`: list sort a'"
1 2 3 4 5 6 7 8 9</lang>
1 2 3 4 5 6 7 8 9</syntaxhighlight>


=== Mata ===
=== Mata ===
See Mata's '''[http://www.stata.com/help.cgi?mf_sort sort]''' function.
See Mata's '''[http://www.stata.com/help.cgi?mf_sort sort]''' function.


<lang stata>mata
<syntaxhighlight lang="stata">mata
: a=2\9\4\7\5\3\6\1\8
: a=2\9\4\7\5\3\6\1\8


Line 2,026: Line 2,563:
9 | 9 |
9 | 9 |
+-----+
+-----+
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
===Sort in place===
===Sort in place===
{{works with|Swift|2.x+}}
{{works with|Swift|2.x+}}
<lang swift>var nums = [2, 4, 3, 1, 2]
<syntaxhighlight lang="swift">var nums = [2, 4, 3, 1, 2]
nums.sortInPlace()
nums.sortInPlace()
print(nums)</lang>
print(nums)</syntaxhighlight>
or
or
<lang swift>var nums = [2, 4, 3, 1, 2]
<syntaxhighlight lang="swift">var nums = [2, 4, 3, 1, 2]
nums.sortInPlace(<)
nums.sortInPlace(<)
print(nums)</lang>
print(nums)</syntaxhighlight>


{{works with|Swift|1.x}}
{{works with|Swift|1.x}}
<lang swift>var nums = [2, 4, 3, 1, 2]
<syntaxhighlight lang="swift">var nums = [2, 4, 3, 1, 2]
nums.sort(<)
nums.sort(<)
println(nums)</lang>
println(nums)</syntaxhighlight>
or
or
<lang swift>var nums = [2, 4, 3, 1, 2]
<syntaxhighlight lang="swift">var nums = [2, 4, 3, 1, 2]
sort(&nums)
sort(&nums)
println(nums)</lang>
println(nums)</syntaxhighlight>
or
or
<lang swift>var nums = [2, 4, 3, 1, 2]
<syntaxhighlight lang="swift">var nums = [2, 4, 3, 1, 2]
sort(&nums, <)
sort(&nums, <)
println(nums)</lang>
println(nums)</syntaxhighlight>


===Return new array===
===Return new array===
Line 2,056: Line 2,593:


{{works with|Swift|2.x+}}
{{works with|Swift|2.x+}}
<lang swift>let nums = [2,4,3,1,2].sort()
<syntaxhighlight lang="swift">let nums = [2,4,3,1,2].sort()
print(nums)</lang>
print(nums)</syntaxhighlight>
or
or
<lang swift>let nums = [2,4,3,1,2].sort(<)
<syntaxhighlight lang="swift">let nums = [2,4,3,1,2].sort(<)
print(nums)</lang>
print(nums)</syntaxhighlight>


{{works with|Swift|1.x}}
{{works with|Swift|1.x}}
<lang swift>let nums = sorted([2,4,3,1,2])
<syntaxhighlight lang="swift">let nums = sorted([2,4,3,1,2])
println(nums)</lang>
println(nums)</syntaxhighlight>
or
or
<lang swift>let nums = [2,4,3,1,2].sorted(<)
<syntaxhighlight lang="swift">let nums = [2,4,3,1,2].sorted(<)
println(nums)</lang>
println(nums)</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set result [lsort -integer $unsorted_list]</lang>
<syntaxhighlight lang="tcl">set result [lsort -integer $unsorted_list]</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 2,081: Line 2,618:
This can be done by using the bubble sort library:
This can be done by using the bubble sort library:


<lang toka>needs bsort
<syntaxhighlight lang="toka">needs bsort
arrayname number_elements bsort</lang>
arrayname number_elements bsort</syntaxhighlight>


See the Toka entry on [[Bubble Sort]] for a full example.
See the Toka entry on [[Bubble Sort]] for a full example.
Line 2,089: Line 2,626:
Each shell parameter separates the integers using the default IFS whitespace (space, tab, newline).
Each shell parameter separates the integers using the default IFS whitespace (space, tab, newline).


<lang bash>nums="2 4 3 1 5"
<syntaxhighlight lang="bash">nums="2 4 3 1 5"
sorted=`printf "%s\n" $nums | sort -n`
sorted=`printf "%s\n" $nums | sort -n`
echo $sorted # prints 1 2 3 4 5</lang>
echo $sorted # prints 1 2 3 4 5</syntaxhighlight>


Alternate solution: <tt>sorted=`for i in $nums; do echo $i; done | sort -n`</tt>
Alternate solution: <tt>sorted=`for i in $nums; do echo $i; done | sort -n`</tt>
Line 2,099: Line 2,636:


{{works with|pdksh|5.2.14}}
{{works with|pdksh|5.2.14}}
<lang bash>set -A nums 2 4 3 1 5
<syntaxhighlight lang="bash">set -A nums 2 4 3 1 5
set -A sorted $(printf "%s\n" ${nums[*]} | sort -n)
set -A sorted $(printf "%s\n" ${nums[*]} | sort -n)
echo ${sorted[*]} # prints 1 2 3 4 5</lang>
echo ${sorted[*]} # prints 1 2 3 4 5</syntaxhighlight>


Users of [[bash]], [[ksh93]] and [[mksh]] can probably use the <tt>nums=(2 4 3 1 2)</tt> syntax.
Users of [[bash]], [[ksh93]] and [[mksh]] can probably use the <tt>nums=(2 4 3 1 2)</tt> syntax.


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl int<> nums
<syntaxhighlight lang="ursa">decl int<> nums
append 2 4 3 1 2 nums
append 2 4 3 1 2 nums
sort nums</lang>
sort nums</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
using the built in sort operator, -<, with the nleq library function
using the built in sort operator, -<, with the nleq library function
for comparing natural numbers
for comparing natural numbers
<lang Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat


#cast %nL
#cast %nL


example = nleq-< <39,47,40,53,14,23,88,52,78,62,41,92,88,66,5,40></lang>
example = nleq-< <39,47,40,53,14,23,88,52,78,62,41,92,88,66,5,40></syntaxhighlight>
output:
output:
<pre><5,14,23,39,40,40,41,47,52,53,62,66,78,88,88,92></pre>
<pre><5,14,23,39,40,40,41,47,52,53,62,66,78,88,88,92></pre>

=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
mut nums := [3, 2, 4, 1, 6, 7, 5, 0]
nums.sort()
println(nums)
}</syntaxhighlight>

{{out}}
<pre>
[0, 1, 2, 3, 4, 5, 6, 7]
</pre>


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang WDTE>let a => import 'arrays';
<syntaxhighlight lang="wdte">let a => import 'arrays';
a.sort [39; 47; 40; 53; 14; 23; 88; 52; 78; 62; 41; 92; 88; 66; 5; 40] < -- io.writeln io.stdout;</lang>
a.sort [39; 47; 40; 53; 14; 23; 88; 52; 78; 62; 41; 92; 88; 66; 5; 40] < -- io.writeln io.stdout;</syntaxhighlight>


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@sort [39 47 40 53 14 23 88 52 78 62 41 92 88 66 5 40]</lang>
<syntaxhighlight lang="wortel">@sort [39 47 40 53 14 23 88 52 78 62 41 92 88 66 5 40]</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-sort}}
{{libheader|Wren-sort}}
<lang ecmascript>import "/sort" for Sort
<syntaxhighlight lang="wren">import "./sort" for Sort


var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5]
var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5]
Sort.quick(a)
Sort.quick(a)
System.print(a)</lang>
System.print(a)</syntaxhighlight>


{{out}}
{{out}}
Line 2,142: Line 2,691:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations


proc SSort(A, N); \Shell sort array in ascending order
proc SSort(A, N); \Shell sort array in ascending order
Line 2,168: Line 2,717:
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


Output:
Output:
Line 2,176: Line 2,725:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>export sub shell_sort(x())
<syntaxhighlight lang="yabasic">export sub shell_sort(x())
// Shell sort based on insertion sort
// Shell sort based on insertion sort


Line 2,231: Line 2,780:
next n
next n


end if</lang>
end if</syntaxhighlight>


=={{header|Yorick}}==
=={{header|Yorick}}==
In Yorick, ''sort'' returns an index list into the array that will put it in sorted order.
In Yorick, ''sort'' returns an index list into the array that will put it in sorted order.
<lang yorick>
<syntaxhighlight lang="yorick">
nums = [2,4,3,1,2];
nums = [2,4,3,1,2];
nums = nums(sort(nums));
nums = nums(sort(nums));
</syntaxhighlight>
</lang>


=={{header|zkl}}==
=={{header|zkl}}==
In place sorting read/write list:
In place sorting read/write list:
<lang zkl>a:=L(4,5,2,6); a.sort(); a.println() //--> L(2,4,5,6)</lang>
<syntaxhighlight lang="zkl">a:=L(4,5,2,6); a.sort(); a.println() //--> L(2,4,5,6)</syntaxhighlight>
Sort a read only list:
Sort a read only list:
<lang zkl>a:=T(4,5,2,6); b:=a.sort();
<syntaxhighlight lang="zkl">a:=T(4,5,2,6); b:=a.sort();
b.println(); //--> L(2,4,5,6)
b.println(); //--> L(2,4,5,6)
a.println(); //--> L(4,5,2,6)</lang>
a.println(); //--> L(4,5,2,6)</syntaxhighlight>


=={{header|Zoea}}==
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: sort_integer_array
program: sort_integer_array
input: [2,4,3,1]
input: [2,4,3,1]
output: [1,2,3,4]
output: [1,2,3,4]
</syntaxhighlight>
</lang>

=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/Sort_integer_array.png Sort integer array]

Latest revision as of 10:48, 8 February 2024

Task
Sort an integer array
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Sort an array (or list) of integers in ascending numerical order.


Use a sorting facility provided by the language/library if possible.

11l

Translation of: Python
nums = [2,4,3,1,2]
nums.sort()

You could also use the built-in sorted() function:

nums = sorted([2,4,3,1,2])

4D

English

ARRAY INTEGER($nums;0)
APPEND TO ARRAY($nums;2)
APPEND TO ARRAY($nums;4)
APPEND TO ARRAY($nums;3)
APPEND TO ARRAY($nums;1)
APPEND TO ARRAY($nums;2)
SORT ARRAY($nums)  ` sort in ascending order
SORT ARRAY($nums;<)  ` sort in descending order

Français

TABLEAU ENTIER($nombres;0)
AJOUTER A TABLEAU($nombres;2)
AJOUTER A TABLEAU($nombres;4)
AJOUTER A TABLEAU($nombres;3)
AJOUTER A TABLEAU($nombres;1)
AJOUTER A TABLEAU($nombres;2)
TRIER TABLEAU($nombres)  ` pour effectuer un tri par ordre croissant
TRIER TABLEAU($nombres;<)  ` pour effectuer un tri par ordre décroissant

8th

[ 10,2,100 ] ' n:cmp a:sort . cr

Output is: [2,10,100]

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program integerSort64.s  with selection 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 
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:       .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                                              // entry of program 
    ldr x0,qAdrTableNumber                         // address number table
    mov x1,0
    mov x2,NBELEMENTS                              // number of élements 
    bl selectionSort
    ldr x0,qAdrTableNumber                         // address number table
    bl displayTable
 
    ldr x0,qAdrTableNumber                         // address number table
    mov x1,NBELEMENTS                              // number of élements 
    bl isSorted                                    // control sort
    cmp x0,1                                       // sorted ?
    beq 1f                                    
    ldr x0,qAdrszMessSortNok                       // no !! error sort
    bl affichageMess
    b 100f
1:                                                 // yes
    ldr x0,qAdrszMessSortOk
    bl affichageMess
100:                                               // standard end of the program 
    mov x0,0                                       // return code
    mov x8,EXIT                                    // request to exit program
    svc 0                                          // perform the system call
 
qAdrsZoneConv:            .quad sZoneConv
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsMessResult:          .quad sMessResult
qAdrTableNumber:          .quad TableNumber
qAdrszMessSortOk:         .quad szMessSortOk
qAdrszMessSortNok:        .quad szMessSortNok
/******************************************************************/
/*     control sorted table                                   */ 
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements  > 0  */
/* x0 return 0  if not sorted   1  if sorted */
isSorted:
    stp x2,lr,[sp,-16]!              // save  registers
    stp x3,x4,[sp,-16]!              // save  registers
    mov x2,0
    ldr x4,[x0,x2,lsl 3]
1:
    add x2,x2,1
    cmp x2,x1
    bge 99f
    ldr x3,[x0,x2, lsl 3]
    cmp x3,x4
    blt 98f
    mov x4,x3
    b 1b
98:
    mov x0,0                       // not sorted
    b 100f
99:
    mov x0,1                       // sorted
100:
    ldp x3,x4,[sp],16              // restaur  2 registers
    ldp x2,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
/******************************************************************/
/*         selection sort                                              */ 
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element    */
/* x2 contains the number of element */
selectionSort:
    stp x1,lr,[sp,-16]!              // save  registers
    stp x2,x3,[sp,-16]!              // save  registers
    stp x4,x5,[sp,-16]!              // save  registers
    stp x6,x7,[sp,-16]!              // save  registers
    mov x3,x1                        // start index i
    sub x7,x2,1                      // compute n - 1
1:                                   // start loop
    mov x4,x3
    add x5,x3,1                      // init index 2
2: 
    ldr x1,[x0,x4,lsl 3]             // load value A[mini]
    ldr x6,[x0,x5,lsl 3]             // load value A[j]
    cmp x6,x1                        // compare value
    csel x4,x5,x4,lt                 // j -> mini
    add x5,x5,1                      // increment index j
    cmp x5,x2                        // end ?
    blt 2b                           // no -> loop
    cmp x4,x3                        // mini <> j ?
    beq 3f                           // no
    ldr x1,[x0,x4,lsl 3]             // yes swap A[i] A[mini]
    ldr x6,[x0,x3,lsl 3]
    str x1,[x0,x3,lsl 3]
    str x6,[x0,x4,lsl 3]
3:
    add x3,x3,1                      // increment i
    cmp x3,x7                        // end ?
    blt 1b                           // no -> loop 
 
100:
    ldp x6,x7,[sp],16                // restaur  2 registers
    ldp x4,x5,[sp],16                // restaur  2 registers
    ldp x2,x3,[sp],16                // restaur  2 registers
    ldp x1,lr,[sp],16                // restaur  2 registers
    ret                              // return to address lr x30
 
/******************************************************************/
/*      Display table elements                                */ 
/******************************************************************/
/* x0 contains the address of table */
displayTable:
    stp x1,lr,[sp,-16]!              // save  registers
    stp x2,x3,[sp,-16]!              // save  registers
    mov x2,x0                        // table address
    mov x3,0
1:                                   // loop display table
    ldr x0,[x2,x3,lsl 3]
    ldr x1,qAdrsZoneConv
    bl conversion10                  // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc            // insert result at @ character
    bl affichageMess                 // display message
    add x3,x3,1
    cmp x3,NBELEMENTS - 1
    ble 1b
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
100:
    ldp x2,x3,[sp],16               // restaur  2 registers
    ldp x1,lr,[sp],16               // restaur  2 registers
    ret                             // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

Action!

INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit

PROC PrintArray(INT ARRAY a INT size)
  INT i

  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    PrintI(a(i))
  OD
  Put(']) PutE()
RETURN

PROC Test(INT ARRAY a INT size BYTE order)
  PrintE("Array before sort:")
  PrintArray(a,size)
  SortI(a,size,order)
  PrintE("Array after sort:")
  PrintArray(a,size)
  PutE()
RETURN

PROC Main()
  DEFINE ASCENDING="0"
  INT ARRAY
    a(10)=[1 4 65535 0 3 7 4 8 20 65530],
    b(21)=[10 9 8 7 6 5 4 3 2 1 0
      65535 65534 65533 65532 65531
      65530 65529 65528 65527 65526],
    c(8)=[101 102 103 104 105 106 107 108],
    d(12)=[1 65535 1 65535 1 65535 1
      65535 1 65535 1 65535]
  
  Put(125) PutE() ;clear screen
  Test(a,10,ASCENDING)
  Test(b,21,ASCENDING)
  Test(c,8,ASCENDING)
  Test(d,12,ASCENDING)
RETURN
Output:

Screenshot from Atari 8-bit computer

Array before sort:
[1 4 -1 0 3 7 4 8 20 -6]
Array after sort:
[-6 -1 0 1 3 4 4 7 8 20]

Array before sort:
[10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10]
Array after sort:
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]

Array before sort:
[101 102 103 104 105 106 107 108]
Array after sort:
[101 102 103 104 105 106 107 108]

Array before sort:
[1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
Array after sort:
[-1 -1 -1 -1 -1 -1 1 1 1 1 1 1]

ActionScript

//Comparison function must returns Numbers even though it deals with integers.
function compare(x:int, y:int):Number
{
	return Number(x-y);
}
var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]);
nums.sort(compare);

Ada

Works with: GNAT version GPL 2006
with Gnat.Heap_Sort_G;
 
procedure Integer_Sort is
   -- Heap sort package requires data to be in index values starting at
   -- 1 while index value 0 is used as temporary storage
   type Int_Array is array(Natural range <>) of Integer;
   Values : Int_Array := (0,1,8,2,7,3,6,4,5);
   
   -- define move and less than subprograms for use by the heap sort package
   procedure Move_Int(From : Natural; To : Natural) is
   begin
      Values(To) := Values(From);
   end Move_Int;
   
   function Lt_Int(Left, Right : Natural) return Boolean is
   begin
      return Values(Left) < Values (Right);
   end Lt_Int;
  
   -- Instantiate the generic heap sort package
   package Heap_Sort is new Gnat.Heap_Sort_G(Move_Int, Lt_Int);

begin
   Heap_Sort.Sort(8);
end Integer_Sort;

requires an Ada05 compiler, e.g GNAT GPL 2007
with Ada.Containers.Generic_Array_Sort;
 
procedure Integer_Sort is
   -- 
   type Int_Array is array(Natural range <>) of Integer;
   Values : Int_Array := (0,1,8,2,7,3,6,4,5);
   
   -- Instantiate the generic sort package from the standard Ada library
   procedure Sort is new Ada.Containers.Generic_Array_Sort
     (Index_Type   => Natural,
      Element_Type => Integer,
      Array_Type   => Int_Array);

begin
   Sort(Values);
end Integer_Sort;

ALGOL 68

Translation of: python
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
CO PR READ "shell_sort.a68" PR CO
MODE TYPE = INT;

PROC in place shell sort = (REF[]TYPE seq)REF[]TYPE:(
    INT inc := ( UPB seq + LWB seq + 1 ) OVER 2;
    WHILE inc NE 0 DO
        FOR index FROM LWB seq TO UPB seq DO
            INT i := index;
            TYPE el = seq[i];
            WHILE ( i  - LWB seq >= inc | seq[i - inc] > el | FALSE ) DO
                seq[i] := seq[i - inc];
                i -:= inc
            OD;
            seq[i] := el
        OD;
        inc := IF inc = 2 THEN 1 ELSE ENTIER(inc * 5 / 11) FI
    OD;  
    seq  
);    
   
PROC shell sort = ([]TYPE seq)[]TYPE:
  in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq);

print((shell sort((2, 4, 3, 1, 2)), new line))

Output:

         +1         +2         +2         +3         +4

ALGOL W

Algol W doesn't have standard sorting facilities. This uses the Algol W quicksort sample in the Sorting Algorithms Quicksort task.

begin
    % use the quicksort procedure from the Sorting_Algorithms/Quicksort task %
    % Quicksorts in-place the array of integers v, from lb to ub - external  %
    procedure quicksort ( integer array v( * )
                        ; integer value lb, ub
                        ) ; algol "sortingAlgorithms_Quicksort" ;
    % sort an integer array with the quicksort routine                       %
    begin
        integer array t ( 1 :: 5 );
        integer p;
        p := 1;
        for v := 2, 3, 1, 9, -2 do begin t( p ) := v; p := p + 1; end;
        quicksort( t, 1, 5 );
        for i := 1 until 5 do writeon( i_w := 1, s_w := 1, t( i ) )
    end
end.
Output:
-2 1 2 3 9

APL

Works with: APL2
      X63 92 51 92 39 15 43 89 36 69
      X[X]
15 36 39 43 51 63 69 89 92 92

AppleScript

AppleScript has no native sort function.

Later versions of AppleScript (OS X 10.10 onwards) do allow access to the ObjC NSArray library, but while this approach can yield reasonably fast sorts, it is slow in terms of scripter time, requiring digestion of the ObjC library documentation, and leading to code like the sort function below, which is possibly more messy than it is worth for the purposes of casual end-user scripting, for which AppleScript was presumably designed.

use framework "Foundation"

-- sort :: [a] -> [a]
on sort(lst)
    ((current application's NSArray's arrayWithArray:lst)'s ¬
        sortedArrayUsingSelector:"compare:") as list
end sort

-- TEST -----------------------------------------------------------------------
on run
    
    map(sort, [[9, 1, 8, 2, 8, 3, 7, 0, 4, 6, 5], ¬
        ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", ¬
            "theta", "iota", "kappa", "lambda", "mu"]])
    
end run


-- GENERIC FUNCTIONS  ---------------------------------------------------------

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
{{0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9}, 
{"alpha", "beta", "delta", "epsilon", "eta", "gamma", 
"iota", "kappa", "lambda", "mu", "theta", "zeta"}}

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program integerSort.s  with selection 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
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:            .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                                              @ entry of program 
 
1:
    ldr r0,iAdrTableNumber                         @ address number table
    mov r1,#0
    mov r2,#NBELEMENTS                             @ number of élements 
    bl selectionSort
    ldr r0,iAdrTableNumber                         @ address number table
    bl displayTable
 
    ldr r0,iAdrTableNumber                         @ address number table
    mov r1,#NBELEMENTS                             @ number of élements 
    bl isSorted                                    @ control sort
    cmp r0,#1                                      @ sorted ?
    beq 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]
1:
    add r2,#1
    cmp r2,r1
    movge r0,#1
    bge 100f
    ldr r3,[r0,r2, lsl #2]
    cmp r3,r4
    movlt r0,#0
    blt 100f
    mov r4,r3
    b 1b
100:
    pop {r2-r4,lr}
    bx lr                                              @ return 
/******************************************************************/
/*         selection sort                                              */ 
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element    */
/* r2 contains the number of element */
selectionSort:
    push {r1-r7,lr}                                        @ save registers
    mov r3,r1                                              @ start index i
    sub r7,r2,#1                                           @ compute n - 1
1:                                                         @ start loop
    mov r4,r3
    add r5,r3,#1                                           @ init index 2
2: 
    ldr r1,[r0,r4,lsl #2]                                  @ load value A[mini]
    ldr r6,[r0,r5,lsl #2]                                  @ load value A[j]
    cmp r6,r1                                              @ compare value
    movlt r4,r5                                            @ j -> mini
    add r5,#1                                              @ increment index j
    cmp r5,r2                                              @ end ?
    blt 2b                                                 @ no -> loop
    cmp r4,r3                                              @ mini <> j ?
    beq 3f                                                 @ no
    ldr r1,[r0,r4,lsl #2]                                  @ yes swap A[i] A[mini]
    ldr r6,[r0,r3,lsl #2]
    str r1,[r0,r3,lsl #2]
    str r6,[r0,r4,lsl #2]
3:
    add r3,#1                                              @ increment i
    cmp r3,r7                                              @ end ?
    blt 1b                                                 @ no -> loop 
 
100:
    pop {r1-r7,lr}
    bx lr                                                  @ return 
 
/******************************************************************/
/*      Display table elements                                */ 
/******************************************************************/
/* r0 contains the address of table */
displayTable:
    push {r0-r3,lr}                                    @ save registers
    mov r2,r0                                          @ table address
    mov r3,#0
1:                                                     @ loop display table
    ldr r0,[r2,r3,lsl #2]
    ldr r1,iAdrsZoneConv                               @ 
    bl conversion10                                    @ décimal conversion 
    ldr r0,iAdrsMessResult
    ldr r1,iAdrsZoneConv                               @ insert conversion
    bl strInsertAtCharInc
    bl affichageMess                                   @ display message
    add r3,#1
    cmp r3,#NBELEMENTS - 1
    ble 1b
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
100:
    pop {r0-r3,lr}
    bx lr
iAdrsZoneConv:           .int sZoneConv
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"

Arturo

arr: [2 3 5 8 4 1 6 9 7]
sort 'arr ; in-place
 
loop arr => print
Output:
1
2
3
4
5
6
7
8
9

AutoHotkey

numbers = 5 4 1 2 3
sort, numbers, N D%A_Space%
Msgbox % numbers

AWK

# syntax: GAWK -f SORT_AN_INTEGER_ARRAY.AWK
BEGIN {
    split("9,10,3,1234,99,1,200,2,0,-2",arr,",")
    show("@unsorted","unsorted")
    show("@val_num_asc","sorted ascending")
    show("@val_num_desc","sorted descending")
    exit(0)
}
function show(sequence,description,  i) {
    PROCINFO["sorted_in"] = sequence
    for (i in arr) {
      printf("%s ",arr[i])
    }
    printf("\t%s\n",description)
}

output:

9 10 3 1234 99 1 200 2 0 -2     unsorted
-2 0 1 2 3 9 10 99 200 1234     sorted ascending
1234 200 99 10 9 3 2 1 0 -2     sorted descending

Axe

There is no ascending sort function in Axe, but there is a descending sort function. One can either implement a custom ascending sorting function or simply reverse the output from SortD.

2→{L₁}
4→{L₁+1}
3→{L₁+2}
1→{L₁+3}
2→{L₁+4}

SortD(L₁,5)

Babel

Use the sortval operator to sort an array of integers (val-array in Babel terminology). The following code creates a list of random values, converts it to a val-array, sorts that val-array, then converts it back to a list for display using the lsnum utility.

babel> nil { zap {1 randlf 100 rem} 20 times collect ! } nest dup lsnum ! --> Create a list of random numbers
( 20 47 69 71 18 10 92 9 56 68 71 92 45 92 12 7 59 55 54 24 )
babel> ls2lf                                                              --> Convert list to array for sorting
babel> dup {fnord} merge_sort                                             --> The internal sort operator
babel> ar2ls lsnum !                                                      --> Display the results
( 7 9 10 12 18 20 24 45 47 54 55 56 59 68 69 71 71 92 92 92 )

In Babel, lists and arrays are distinct. If you want to sort a list, use the lssort utility:

babel> ( 68 73 63 83 54 67 46 53 88 86 49 75 89 83 28 9 34 21 20 90 )
babel> {lt?} lssort ! lsnum !
( 9 20 21 28 34 46 49 53 54 63 67 68 73 75 83 83 86 88 89 90 )

To reverse the sort-order, use the 'gt?' predicate instead of the 'lt?' predicate:

babel> ( 68 73 63 83 54 67 46 53 88 86 49 75 89 83 28 9 34 21 20 90 ) {gt?} lssort ! lsnum !
( 90 89 88 86 83 83 75 73 68 67 63 54 53 49 46 34 28 21 20 9 )

BaCon

' Sort an integer array
DECLARE values[5] TYPE NUMBER
values[0] = 23
values[1] = 32
values[2] = 12
values[3] = 21
values[4] = 01

SORT values

FOR i = 0 TO 3
    PRINT values[i], ", ";
NEXT
PRINT values[4]
Output:
prompt$ ./sort-integer
1, 12, 21, 23, 32

Use SORT array DOWN for descending sort order.

BBC BASIC

Uses the supplied SORTLIB library.

      INSTALL @lib$+"SORTLIB"
      sort% = FN_sortinit(0,0)
      
      DIM array(8)
      array() = 8, 2, 5, 9, 1, 3, 6, 7, 4
      
      C% = DIM(array(),1) + 1
      CALL sort%, array(0)
      
      FOR i% = 0 TO DIM(array(),1) - 1
        PRINT ; array(i%) ", ";
      NEXT
      PRINT ; array(i%)

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9

Beads

beads 1 program 'Sort an integer array'
calc main_init
	var arr = [4, 1, 2, -1, 3, 0, 2]
	var newarr : array of num
	loop across:arr sort:val count:c val:v
		newarr[c] = v

Befunge

Works with: befungee

Elements of the array are read from standard input, preceded by their quantity. The algorithm uses counting sort and allows numbers between 1 and 60, inclusive.

v 
> 543** >     :#v_ $&>           :#v_ 1 > :0g >    :#v_ $ 1+: 543** `! #v_ 25*,@
        ^-1p0\0:<    ^-1 p0\+1 g0:&<          ^-1\.:\<
                                        ^                               <

BQN

 [4, 1, 2, ¯9, ¯5, 3, 6, 9, ¯2]
Output:
⟨ ¯9 ¯5 ¯2 1 2 3 4 6 9 ⟩

Bracmat

As a Computer Algebra system, Bracmat transforms expressions to a canonical form. Terms in a sum are sorted and, where possible, added together. So the task is partially solved by expressing the list as a sum of terms. Evaluating the list sorts the list, but also adds like terms. To illustrate, this is what happens when entering our list at the prompt:

{?} (9.)+(-2.)+(1.)+(2.)+(8.)+(0.)+(1.)+(2.)
{!} (-2.)+(0.)+2*(1.)+2*(2.)+(8.)+(9.)

The use of a computationally inert operator like the dot . is essential:

{?} (9)+(-2)+(1)+(2)+(8)+(0)+(1)+(2)
{!} 21

To complete the task need to unfold the terms with a numerical factor >1:

{sort takes a list of space-separated integers}
(sort=
  sum elem sorted n
.   0:?sum
  &   whl
    ' (!arg:%?elem ?arg&(!elem.)+!sum:?sum)
  & :?sorted
  &   whl
    ' ( !sum:?n*(?elem.)+?sum
      &   whl
        ' ( !n+-1:~<0:?n
          & !sorted !elem:?sorted
          )
      )
  & !sorted);
  
  out$sort$(9 -2 1 2 8 0 1 2);
Output:
-2 0 1 1 2 2 8 9

This solution becomes very ineffective for long lists. To add a single term to an already sorted sum of N terms requires on average N/2 steps. It is much more efficient to merge two already sorted sums of about equal length. Also, adding elements to the end of the list 'sorted' is costly. Better is to prepend elements to a list, which will have inverted sorting order, and to invert this list in an extra loop.

Burlesque

{1 3 2 5 4}><

C

#include <stdlib.h>  /* qsort() */
#include <stdio.h>   /* printf() */

int intcmp(const void *aa, const void *bb)
{
    const int *a = aa, *b = bb;
    return (*a < *b) ? -1 : (*a > *b);
}

int main()
{
    int nums[5] = {2,4,3,1,2};
    qsort(nums, 5, sizeof(int), intcmp);
    printf("result: %d %d %d %d %d\n",
      nums[0], nums[1], nums[2], nums[3], nums[4]);
    return 0;
}

Caution: An older version of intcmp() did return *a - *b. This is only correct when the subtraction does not overflow. Suppose that *a = 2000000000 and *b = -2000000000 on a machine with 32-bit int. The subtraction *a - *b would overflow to -294967296, and intcmp() would believe *a < *b, but the correct answer is *a > *b.

C#

using System;
using System.Collections.Generic;

public class Program {
    static void Main() {
        int[] unsorted = { 6, 2, 7, 8, 3, 1, 10, 5, 4, 9 };
        Array.Sort(unsorted);
    }
}

C++

Works with: g++ version 4.0.1

Simple Array

#include <algorithm>

int main()
{
    int nums[] = {2,4,3,1,2};
    std::sort(nums, nums+sizeof(nums)/sizeof(int));
    return 0;
}

std::vector

#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> nums;
    nums.push_back(2);
    nums.push_back(4);
    nums.push_back(3);
    nums.push_back(1);
    nums.push_back(2);
    std::sort(nums.begin(), nums.end());
    return 0;
}

std::list

#include <list>

int main()
{
    std::list<int> nums;
    nums.push_back(2);
    nums.push_back(4);
    nums.push_back(3);
    nums.push_back(1);
    nums.push_back(2);
    nums.sort();
    return 0;
}

Clean

We use list and array comprehensions to convert an array to and from a list in order to use the built-in sort on lists.

import StdEnv

sortArray :: (a e) -> a e | Array a e & Ord e
sortArray array = {y \\ y <- sort [x \\ x <-: array]}

Start :: {#Int}
Start = sortArray {2, 4, 3, 1, 2}

Clojure

(sort [5 4 3 2 1]) ; sort can also take a comparator function
(1 2 3 4 5)

COBOL

Works with: Visual COBOL
       PROGRAM-ID. sort-ints.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  array-area             VALUE "54321".
           03  array              PIC 9 OCCURS 5 TIMES.
       01  i                      PIC 9.
       
       PROCEDURE DIVISION.
       main-line.
           PERFORM display-array
           SORT array ASCENDING array
           PERFORM display-array
       
           GOBACK
           .
       display-array.
           PERFORM VARYING i FROM 1 BY 1 UNTIL 5 < i
               DISPLAY array (i) " " NO ADVANCING
           END-PERFORM
           DISPLAY SPACE
           .

Common Lisp

In Common Lisp, the sort function takes a predicate that is used as the comparator. This parameter can be any two-argument function. To sort a sequence (list or array) of integers, call sort with the < operator as the predicate:

CL-USER> (sort #(9 -2 1 2 8 0 1 2) #'<)
#(-2 0 1 1 2 2 8 9)

Crystal

Example demonstrating the support for copy sort and in-place sort (like Ruby)

a = [5, 4, 3, 2, 1]
puts a.sort
# => [1, 2, 3, 4, 5]

puts a
# => [5, 4, 3, 2, 1]

a.sort!
puts a
# => [1, 2, 3, 4, 5]

D

import std.stdio, std.algorithm;

void main() {
    auto data = [2, 4, 3, 1, 2];
    data.sort(); // in-place
    assert(data == [1, 2, 2, 3, 4]);
}

Delphi

uses Types, Generics.Collections;

var
  a: TIntegerDynArray;
begin
  a := TIntegerDynArray.Create(5, 4, 3, 2, 1);
  TArray.Sort<Integer>(a);
end;

DWScript

var a : array of Integer := [5, 4, 3, 2, 1];
a.Sort; // ascending natural sort
PrintLn(a.Map(IntToStr).Join(','));  // 1,2,3,4,5

Déjà Vu

!. sort [ 5 4 3 2 1 ]
Output:
[ 1 2 3 4 5 ]

E

[2,4,3,1,2].sort()

EGL

Works with: EDT

The following works in EDT with Rich UI and stand-alone programs.

program SortExample

    function main()
        test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0];
        test1.sort(sortFunction);

	for(i int from 1 to test1.getSize())
	    SysLib.writeStdout(test1[i]);
	end
    end
    
    function sortFunction(a any in, b any in) returns (int)
        return (a as int) - (b as int);
    end
	
end
Works with: RBD

The following works in RBD but only with Rich UI programs.

test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0];
RUILib.sort(test1, sortFunction);

    
function sortFunction(a any in, b any in) returns (int)
    return ((a as int) - (b as int));
end

Eiffel

Full example code

Using a SORTED_TWO_WAY_LIST means that the contents of the list will be sorted ascending automatically. The list can be easily sorted in reverse. There is a call for `sort' to manually initiate sorting.

local
	l_array: SORTED_TWO_WAY_LIST [INTEGER]
do
	create l_array.make_from_iterable (<<9,8,7,6,5,4,3,2,1,0>>)
end

Elena

ELENA 5.0 :

import system'routines;
import extensions;
 
public program()
{
    var unsorted := new int[]{6, 2, 7, 8, 3, 1, 10, 5, 4, 9};
 
    console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable())
}

Elixir

list = [2, 4, 3, 1, 2]
IO.inspect Enum.sort(list)
IO.inspect Enum.sort(list, &(&1>&2))
Output:
[1, 2, 2, 3, 4]
[4, 3, 2, 2, 1]

Erlang

List = [2, 4, 3, 1, 2].
SortedList = lists:sort(List).

Euphoria

include sort.e
print(1,sort({20, 7, 65, 10, 3, 0, 8, -60}))

F#

// sorting an array in place
let nums = [| 2; 4; 3; 1; 2 |]
Array.sortInPlace nums

// create a sorted copy of a list
let nums2 = [2; 4; 3; 1; 2]
let sorted = List.sort nums2

Factor

{ 1 4 9 2 3 0 5 } natural-sort .

Fantom

The List collection contains a sort method which uses the usual comparison method for the data in the list; the sort is done 'in place'.

fansh> a := [5, 1, 4, 2, 3]
[5, 1, 4, 2, 3]
fansh> a.sort
[1, 2, 3, 4, 5]
fansh> a
[1, 2, 3, 4, 5]

Forth

Works with: Win32Forth version 4.2

Win32Forth

create test-data 2 , 4 , 3 , 1 , 2 ,
test-data 5 cell-sort

ANS/ISO Forth

Works with: GForth

Uses quicksort http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Forth

Standard Forth does not have a library sort

100000 CONSTANT SIZE

CREATE MYARRAY   SIZE CELLS ALLOT

: []   ( n addr -- addr[n])  SWAP CELLS + ;

: FILLIT ( -- ) ( reversed order)
  SIZE 0  DO   SIZE I -   I MYARRAY [] !  LOOP ;

: SEEIT  ( -- ) 
  SIZE 0 DO  I MYARRAY [] ?   LOOP ;

\ define non-standard words used by Quicksort author
1 CELLS CONSTANT CELL
CELL NEGATE CONSTANT -CELL
: CELL-   CELL - ;

: MID ( l r -- mid ) OVER - 2/ -CELL AND + ;

: EXCH    ( addr1 addr2 -- ) 
  OVER @ OVER @        ( read values)
  SWAP ROT ! SWAP ! ;  ( exchange values)

: PARTITION ( l r -- l r r2 l2 )
  2DUP MID @ >R ( r: pivot )
  2DUP
  BEGIN
    SWAP BEGIN  DUP @  R@  < WHILE CELL+ REPEAT
    SWAP BEGIN  R@ OVER @  < WHILE CELL- REPEAT
    2DUP <= IF 2DUP EXCH  >R CELL+ R> CELL-  THEN
    2DUP >
  UNTIL
  R> DROP ;

: QSORT ( l r -- )
  PARTITION  SWAP ROT
  2DUP < IF RECURSE ELSE 2DROP THEN
  2DUP < IF RECURSE ELSE 2DROP THEN ;

: QUICKSORT ( array len -- )
  DUP 2 < IF 2DROP EXIT THEN  1- CELLS OVER + QSORT ;</LANG>
Test at the console
<syntaxhighlight lang="forth">FILLIT ok
MYARRAY SIZE QUICKSORT ok

Fortran

Works with: Silverfrost FTN95
CALL ISORT@(b, a, n)
! n = number of elements
! a = array to be sorted
! b = array of indices of a. b(1) 'points' to the minimum value etc.

FreeBASIC

Qsort is not buildin, but include in the compiler package.

' version 11-03-2016
' compile with: fbc -s console

#Include Once "crt/stdlib.bi"      ' needed for qsort subroutine

' Declare Sub qsort (ByVal As Any Ptr, <== point to start of array
'                    ByVal As size_t,  <== size of array
'                    ByVal As size_t,  <== size of array element
' ByVal As Function(ByVal As Any Ptr, ByVal As Any Ptr) As Long)  <== callback function
' declare callback function with Cdecl to ensures that the parameters are passed in the correct order
'
' size of long: 4 bytes on 32bit OS, 8 bytes on 64bit OS

' ascending
 Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
     Function = *Cast(Long Ptr, element1) - *Cast(Long Ptr, element2)
End Function

' Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
' Dim As Long e1 = *Cast(Long Ptr, element1)
' Dim As Long e2 = *Cast(Long Ptr, element2)
' Dim As Long result = Sgn(e1 - e2)
' If Sgn(e1) = -1 And Sgn(e2) = -1 Then result = -result
'     Function = result
' End Function

' ------=< MAIN >=------

Dim As Long i, array(20)

Dim As Long lb = LBound(array)
Dim As Long ub = UBound(array)

For i = lb To ub     ' fill array
    array(i) = 10 - i
Next

Print
Print "unsorted array"
For i = lb To ub     ' display array
    Print Using "###";array(i);
Next
Print : Print

' sort array
qsort(@array(lb), ub - lb +1, SizeOf(array), @callback)

Print "sorted array"
For i = lb To ub     ' show sorted array
    Print Using "###";array(i);
Next
Print

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
Output:
unsorted array
 10  9  8  7  6  5  4  3  2  1  0 -1 -2 -3 -4 -5 -6 -7 -8 -9-10

sorted array
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10

Frink

The following sorts an array in-place.

a = [5, 2, 4, 1, 6, 7, 9, 3, 8, 0]
sort[a]

FunL

nums = [5, 2, 78, 2, 578, -42]
println( sort(nums) )           // sort in ascending order
println( nums.sortWith((>)) )   // sort in descending order
Output:
[-42, 2, 2, 5, 78, 578]
[578, 78, 5, 2, 2, -42]

FutureBasic

window 1, @"Sort an integer array"

void local fn DoIt
  CFArrayRef array = @[@13,@71,@42,@8,@5,@27]
  array = fn ArraySortedArrayUsingSelector( array, @"compare:" )
  print fn ArrayComponentsJoinedByString( array, @", " )
end fn

fn DoIt

HandleEvents
Output:
5, 8, 13, 27, 42, 71

Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Gambas

Click this link to run this code

Public Sub Main()
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Dim sOutput As String

For Each iTemp In iArray.Sort()
  sOutput &= iTemp & ", "
Next

Print Left(sOutput, -2)

End

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9

GAP

a := [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ];
# Make a copy (with "b := a;", b and a would point to the same list)
b := ShallowCopy(a);

# Sort in place
Sort(a);
a;
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

# Sort without changing the argument
SortedList(b);
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
b;
# [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ]

Go

package main
import "fmt"
import "sort"

func main() {
  nums := []int {2, 4, 3, 1, 2}
  sort.Ints(nums)
  fmt.Println(nums)
}

Golfscript

[2 4 3 1 2]$

Groovy

println ([2,4,0,3,1,2,-12].sort())

Output:

[-12, 0, 1, 2, 2, 3, 4]

Haskell

Works with: GHCi version 6.6
nums = [2,4,3,1,2] :: [Int]
sorted = List.sort nums

HicEst

DIMENSION array(100)

   array = INT( RAN(100) )
   SORT(Vector=array, Sorted=array)

Huginn

main() {
  nums = [2, 4, 3, 1, 2];
  nums.sort();
}

Icon and Unicon

Icon and Unicon lists allow mixed type and the built-in function 'sort' will deal with mixed type arrays by sorting by type first then value. Integers sort before, reals, strings, lists, tables, etc. As a result a list of mixed numeric valuess (i.e. integers and reals) will not sort by numeric value, rather the reals will appear after the integers. Sort returns a sorted copy of it's argument. It will also perform some type conversion, such converting an unordered set into an ordered list.

In the example below, L will remain an unsorted list and S will be sorted.

S := sort(L:= [63, 92, 51, 92, 39, 15, 43, 89, 36, 69])  # will sort a list

IDL

result = array[sort(array)]

Inform 7

let L be {5, 4, 7, 1, 18};
sort L;

Io

mums := list(2,4,3,1,2)
sorted := nums sort  # returns a new sorted array.  'nums' is unchanged
nums sortInPlace  # sort 'nums' "in-place"

J

/:~

The verb /:~ sorts anything that J can represent. For example:

   ] a=: 10 ?@$ 100    NB. random vector
63 92 51 92 39 15 43 89 36 69
   /:~ a
15 36 39 43 51 63 69 89 92 92

Arrays of any rank are treated as lists of component arrays. Thus /:~ sorts not only atoms within a list, but whole lists within a table, tables within a three-axis array, and so on. The level of structure at which sorting occurs may also be specified, so that /:~"1 sorts the atoms within the finest-grained list within the array, regardless of the overall rank of the array. See the Total Array Ordering essay on the JWiki for more details.

This code also applies to any data type.

Java

Array

import java.util.Arrays;

public class Example {
    public static void main(String[] args)
    {
        int[] nums = {2,4,3,1,2};
        Arrays.sort(nums);
    }
}

List

Works with: Java version 1.5+
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Example {
    public static void main(String[] args)
    {
        List<Integer> nums = Arrays.asList(2,4,3,1,2);
        Collections.sort(nums);
    }
}

JavaScript

Works with: Firefox version 2.0

JavaScript sorts lexically by default, so "10000" comes before "2". To sort numerically, a custom comparator is used.

function int_arr(a, b) {
  return a - b;
}
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
numbers.sort(int_arr);
document.write(numbers);

Jinja

from jinja2 import Template
print(Template("{{ [53, 17, 42, 61, 35] | sort }}").render())

Descending order:

from jinja2 import Template
print(Template("{{ [53, 17, 42, 61, 35] | sort(reverse=true) }}").render())

jq

jq's builtin sort filter sorts the elements of an array in ascending order:

[2,1,3] | sort  # => [1,2,3]

Julia

Julia has both out-of-place (sort) and in-place (sort!) sorting functions in its standard-library:

julia> a = [4,2,3,1]
4-element Int32 Array:
 4
 2
 3
 1
julia> sort(a) #out-of-place/non-mutating sort
4-element Int32 Array:
 1
 2
 3
 4

julia> a
4-element Int32 Array:
 4
 2
 3
 1

julia> sort!(a) # in-place/mutating sort
4-element Int32 Array:
 1
 2
 3
 4

julia> a
4-element Int32 Array:
 1
 2
 3
 4

K

  num: -10?10              / Integers from 0 to 9 in random order
5 9 4 2 0 3 6 1 8 7

  srt: {x@<x}              / Generalized sort ascending
  srt num
0 1 2 3 4 5 6 7 8 9

Kotlin

// version 1.0.6

fun main(args: Array<String>) {
   val ints = intArrayOf(6, 2, 7, 8, 3, 1, 10, 5, 4, 9)
   ints.sort()
   println(ints.joinToString(prefix = "[", postfix = "]"))
}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Lambdatalk

1) sorting digits in a number returns a new number of ordered digits
{W.sort < 51324}
-> 12345

2) sorting a sequence of numbers returns a new ordered sequence of these numbers
{S.sort < 51 111 33 2 41}
-> 2 33 41 51 111

3) sorting an array of numbers returns the same array ordered
{A.sort! < {A.new 51 111 33 2 41}}
-> [2,33,41,51,111]

Lasso

local(array) = array(5,20,3,2,6,1,4)
#array->sort
#array // 1, 2, 3, 4, 5, 6, 20

// Reverse the sort order
#array->sort(false)
#array // 20, 6, 5, 4, 3, 2, 1

Liberty BASIC

LB has an array-sort command. Parameters are arrayname, start term, finish term.

N =20
dim IntArray( N)

print "Original order"
for i =1 to N
    t =int( 1000 *rnd( 1))
    IntArray( i) =t
    print t
next i

sort IntArray(), 1, N

print "Sorted oprder"
for i =1 to N
    print IntArray( i)
next i

Lingo

l = [7, 4, 23]
l.sort()
put l
-- [4, 7, 23]

LiveCode

LiveCode can sort lines or items natively. The delimiter for items can be set to any single character, but defaults to comma.

put "3,2,5,4,1" into X
sort items of X numeric
put X
-- outputs "1,2,3,4,5"

Lua

t = {4, 5, 2}
table.sort(t)
print(unpack(t))

Maple

sort([5,7,8,3,6,1]);
sort(Array([5,7,8,3,6,1]))

Mathematica/Wolfram Language

numbers=Sort[{2,4,3,1,2}]

MATLAB

a = [4,3,7,-2,9,1]; b = sort(a)     % b contains elements of a in ascending order
[b,idx] = sort(a)                   % b contains a(idx)

Maxima

sort([9, 4, 3, 7, 6, 1, 10, 2, 8, 5]);

MAXScript

arr = #(5, 4, 3, 2, 1)
arr = sort arr

Mercury

:- module sort_int_list.
:- interface.
:- import_module io.

:- pred main(io::di, uo::uo) is det.

:- implementation.
:- import_module list.

main(!IO) :-
  Nums = [2, 4, 0, 3, 1, 2],
  list.sort(Nums, Sorted),
  io.write(Sorted, !IO),
  io.nl(!IO).

min

Works with: min version 0.19.3
(5 2 1 3 4) '> sort print
Output:
(1 2 3 4 5)

Modula-3

Modula-3 provides a generic ArraySort module, as well as an instance of that module for integers called IntArraySort.

MODULE ArraySort EXPORTS Main;

IMPORT IntArraySort;

VAR arr := ARRAY [1..10] OF INTEGER{3, 6, 1, 2, 10, 7, 9, 4, 8, 5};

BEGIN
  IntArraySort.Sort(arr);
END ArraySort.

MUMPS

SORTARRAY(X,SEP)
 ;X is the list of items to sort
 ;X1 is the temporary array
 ;SEP is the separator string between items in the list X
 ;Y is the returned list
 ;This routine uses the inherent sorting of the arrays
 NEW I,X1,Y
 SET Y=""
 FOR I=1:1:$LENGTH(X,SEP) SET X1($PIECE(X,SEP,I))=""
 SET I="" FOR  SET I=$O(X1(I)) Q:I=""  SET Y=$SELECT($L(Y)=0:I,1:Y_SEP_I)
 KILL I,X1
 QUIT Y

Output:

USER>W $$SORTARRAY^ROSETTA("3,5,1,99,27,16,0,-1",",")
-1,0,1,3,5,16,27,99

Nanoquery

'sort' in the Nanoquery standard library has a Quicksort function.

% import sort
% println sort({2,4,3,1,2})
[1, 2, 2, 3, 4]

Neko

/**
 <doc><h2>Sort integer array, in Neko</h2>
   <p>Array sort function modified from Haxe codegen with -D neko-source</p>
   <p>The Neko target emits support code for Haxe basics, sort is included</p>
   <p>Tectonics:<br />prompt$ nekoc sort.neko<br />prompt$ neko sort</p>
 </doc>
**/

var sort = function(a) {
    var i = 0;
    var len = $asize(a);
    while ( i < len ) {
        var swap = false;
        var j = 0;
        var max = (len - i) - 1;
        while ( j < max ) {
            if ( (a[j] - a[j + 1]) > 0 ) {
                var tmp = a[j + 1];
                a[j + 1] = a[j];
                a[j] = tmp;
                swap = true;
            }
            j += 1;
        }
        if ( $not(swap) )
            break;;
        i += 1;
    }
    return a;
}

var arr = $array(5,3,2,1,4)
$print(arr, "\n")

/* Sorts in place */
sort(arr)
$print(arr, "\n")

/* Also returns the sorted array for chaining */
$print(sort($array(3,1,4,1,5,9,2,6,5,3,5,8)), "\n")
Output:
prompt$ nekoc sort.neko
prompt$ neko sort.n
[5,3,2,1,4]
[1,2,3,4,5]
[1,1,2,3,3,4,5,5,5,6,8,9]

Nemerle

using System.Console;

module IntSort
{
    Main() : void
    {
        def nums = [1, 5, 3, 7, 2, 8, 3, 9];
        def sorted = nums.Sort((x, y) => x.CompareTo(y));
        
        WriteLine(nums);
        WriteLine(sorted);
    }
}

Output:

[1, 5, 3, 7, 2, 8, 3, 9]
[1, 2, 3, 3, 5, 7, 8, 9]

NetRexx

/* NetRexx */
options replace format comments java crossref savelog symbols binary

ia = int[]
ia = [ 2, 4, 3, 1, 2, -1, 0, -2 ]

display(ia)
Arrays.sort(ia)
display(ia)

-- Display results
method display(in = int[]) public static

  sorted = Rexx('')

  loop ix = 0 for in.length
    sorted = sorted || Rexx(in[ix]).right(4)
    end ix

  say sorted.strip('t')

  return

Output

   2   4   3   1   2  -1   0  -2 
  -2  -1   0   1   2   2   3   4 

NetRexx reimplementations of the Rexx samples from below:

/* NetRexx */
options replace format comments java crossref savelog symbols

/*REXX program to sort an integer array.*/

numeric digits 20    /*handle larger numbers.*/
a = ''
a[ 1]=               1
a[ 2]=               0
a[ 3]=              -1
a[ 4]=               0
a[ 5]=               5
a[ 6]=               0
a[ 7]=             -61
a[ 8]=               0
a[ 9]=            1385
a[10]=               0
a[11]=          -50521
a[12]=               0
a[13]=         2702765
a[14]=               0
a[15]=      -199360981
a[16]=               0
a[17]=     19391512145
a[18]=               0
a[19]=  -2404879675441
a[20]=               0
a[21]= 370371188237525

size = 21                          /*we have a list of 21 Euler numbers.*/
tell('un-sorted', a, size)
a[0] = size
esort(a, 1)
tell('   sorted', a, size)

return

/*----------------------------------ESORT subroutine--------------------*/
method esort(a, size) public static
--esort: procedure expose a.;

  h = a[0]
 
  loop while h > 1
    h = h % 2
    loop i = 1 for a[0] - h
      j = i
      k = h + i
      loop while a[k] < a[j]
        t    = a[j]
        a[j] = a[k]
        a[k] = t
        if h >= j then leave
        j = j - h
        k = k - h
        end
      end i
    end

return

/*----------------------------------TELL subroutine---------------------*/
method tell(arg, a, size) public static
--tell:

  say arg.center(40, '-')
  loop j = 1 for size
    say arg 'array element' j.right(size.length)'='a[j].right(25)
    end j
  say

  return

Output

---------------un-sorted----------------
un-sorted array element  1=                        1
un-sorted array element  2=                        0
un-sorted array element  3=                       -1
un-sorted array element  4=                        0
un-sorted array element  5=                        5
un-sorted array element  6=                        0
un-sorted array element  7=                      -61
un-sorted array element  8=                        0
un-sorted array element  9=                     1385
un-sorted array element 10=                        0
un-sorted array element 11=                   -50521
un-sorted array element 12=                        0
un-sorted array element 13=                  2702765
un-sorted array element 14=                        0
un-sorted array element 15=               -199360981
un-sorted array element 16=                        0
un-sorted array element 17=              19391512145
un-sorted array element 18=                        0
un-sorted array element 19=           -2404879675441
un-sorted array element 20=                        0
un-sorted array element 21=          370371188237525

---------------   sorted----------------
   sorted array element  1=           -2404879675441
   sorted array element  2=               -199360981
   sorted array element  3=                   -50521
   sorted array element  4=                      -61
   sorted array element  5=                       -1
   sorted array element  6=                        0
   sorted array element  7=                        0
   sorted array element  8=                        0
   sorted array element  9=                        0
   sorted array element 10=                        0
   sorted array element 11=                        0
   sorted array element 12=                        0
   sorted array element 13=                        0
   sorted array element 14=                        0
   sorted array element 15=                        0
   sorted array element 16=                        1
   sorted array element 17=                        5
   sorted array element 18=                     1385
   sorted array element 19=                  2702765
   sorted array element 20=              19391512145
   sorted array element 21=          370371188237525
/* NetRexx */
options replace format comments java crossref savelog symbols

/*REXX program to sort an interesting integer list.*/

bell = '1 1 2 5 15 52 203 877 4140 21147 115975'      /*some Bell numbers.*/
bern = '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617'  /*some Bernoulli num*/
perrin = '3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90' /*some Perrin nums. */
list = bell bern perrin                               /*combine the three.*/

size = list.words

a = 0
loop j = 1 for size
  a[j] = list.word(j)
  end j

say '  as is='list
a[0] = size
esort(a, size)
bList = ''

loop j = 1 for size
  bList = bList a[j]
  end j

blist = bList.strip
say ' sorted='bList

return

/*----------------------------------ESORT subroutine--------------------*/
method esort(a, size) public static
--esort: procedure expose a.;

  h = a[0]
 
  loop while h > 1
    h = h % 2
    loop i = 1 for a[0] - h
      j = i
      k = h + i
      loop while a[k] < a[j]
        t    = a[j]
        a[j] = a[k]
        a[k] = t
        if h >= j then leave
        j = j - h
        k = k - h
        end
      end i
    end

return

Output

  as is=1 1 2 5 15 52 203 877 4140 21147 115975 1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90
 sorted=-3617 -691 -1 -1 -1 0 0 0 0 0 0 0 0 1 1 1 1 1 2 2 2 3 3 5 5 5 5 7 7 10 12 15 17 22 29 39 51 52 68 90 203 877 4140 21147 115975

Nial

sort >= 9 6 8 7 1 10
= 10 9 8 7 6 1

Nim

import algorithm
  
var a: array[0..8, int] = [2, 3, 5, 8, 4, 1, 6, 9, 7]
a.sort(Ascending)
for x in a:
  echo x
Output:
1
2
3
4
5
6
7
8
9

Niue

Library

2 6 1 0 3 8 sort .s
0 1 2 3 6 8

Objeck

bundle Default {
  class Sort {
    function : Main(args : System.String[]) ~ Nil {
      nums := Structure.IntVector->New([2,4,3,1,2]);
      nums->Sort();
    }
  }
}

Objective-C

NSArray *nums = @[@2, @4, @3, @1, @2];
NSArray *sorted = [nums sortedArrayUsingSelector:@selector(compare:)];

OCaml

Array

let nums = [|2; 4; 3; 1; 2|]
Array.sort compare nums

List

let nums = [2; 4; 3; 1; 2]
let sorted = List.sort compare nums

Octave

The variable v can be a vector or a matrix (columns will be sorted).

sortedv = sort(v);

Oforth

[ 8, 2, 5, 9, 1, 3, 6, 7, 4 ] sort

ooRexx

a = .array~of(4, 1, 6, -2, 99, -12)
say "The sorted numbers are"
say a~sortWith(.numericComparator~new)~makeString

Output:

The sorted numbers are
-12
-2
1
4
6
99

Order

Passing the less-than operator to the built-in sequence (i.e. list) sort function:

#include <order/interpreter.h>

ORDER_PP( 8seq_sort(8less, 8seq(2, 4, 3, 1, 2)) )

Oz

declare
  Nums = [2 4 3 1 2]
  Sorted = {List.sort Nums Value.'<'}
in
  {Show Sorted}

PARI/GP

vecsort(v)

Peloton

Sorting a list of numbers as strings and as numbers (from the manual.)

Construct a list of numbers 
<@ LETCNSLSTLIT>L|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@> 
Numbers sort as strings
<@ ACTSRTENTLST>L</@> 
<@ SAYDMPLST>L</@> 
<@ ACTSRTENTLSTLIT>L|__StringDescending</@> 
<@ SAYDMPLST>L</@>
 
Construct another list of numbers
<@ LETCNSLSTLIT>list|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@> 
Numbers sorted as numbers
<@ ACTSRTENTLSTLIT>list|__Numeric</@> 
<@ SAYDMPLST>list</@> 
<@ ACTSRTENTLSTLIT>list|__NumericDescending</@> 
<@ SAYDMPLST>list</@>

Output

Construct a list of numbers 
 
Numbers sort as strings
 
1^2^25^25^3^39^4^4^41^42^44^45^47^51^65^69^77^84^ 
 
84^77^69^65^51^47^45^44^42^41^4^4^39^3^25^25^2^1^
 
Construct another list of numbers
 
Numbers sorted as numbers
 
1^2^3^4^4^25^25^39^41^42^44^45^47^51^65^69^77^84^ 
 
84^77^69^65^51^47^45^44^42^41^39^25^25^4^4^3^2^1^

Perl

Works with: Perl version 5.8.6
@nums = (2,4,3,1,2);
@sorted = sort {$a <=> $b} @nums;

Phix

Library: Phix/basics
?sort({9, 10, 3, 1, 4, 5, 8, 7, 6, 2})

Phixmonti

include ..\Utilitys.pmt

( 9 10 3 1 4 5 8 7 6 2 ) sort print

PHP

Works with: PHP version 4.4.4 CLI
<?php
$nums = array(2,4,3,1,2);
sort($nums);
?>

PicoLisp

The sort function in PicoLisp returns already by default an ascending list (of any type, not only integers):

(sort (2 4 3 1 2))
-> (1 2 2 3 4)

PL/I

Works with: IBM PL/I version 7.5
DCL (T(10)) FIXED BIN(31); /* scratch space of length N/2 */

MERGE: PROCEDURE (A,LA,B,LB,C);
   DECLARE (A(*),B(*),C(*)) FIXED BIN(31);
   DECLARE (LA,LB) FIXED BIN(31) NONASGN;
   DECLARE (I,J,K) FIXED BIN(31);
   
   I=1; J=1; K=1;
   DO WHILE ((I <= LA) & (J <= LB));
      IF(A(I) <= B(J)) THEN
         DO; C(K)=A(I); K=K+1; I=I+1; END;
      ELSE
         DO; C(K)=B(J); K=K+1; J=J+1; END;
   END;
   DO WHILE (I <= LA);
      C(K)=A(I); I=I+1; K=K+1;
   END;
   RETURN;
END MERGE;

MERGESORT: PROCEDURE (A,N) RECURSIVE ;
     DECLARE (A(*))               FIXED BINARY(31);
     DECLARE N                    FIXED BINARY(31) NONASGN;
     DECLARE Temp                 FIXED BINARY;
     DECLARE (M,I)                FIXED BINARY;
     DECLARE AMP1(N)              FIXED BINARY(31) BASED(P);
     DECLARE P POINTER;
    IF (N=1) THEN RETURN;
   M = trunc((N+1)/2);
   IF (M>1) THEN CALL MERGESORT(A,M);
   P=ADDR(A(M+1)); 
   IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M);
   IF A(M) <= AMP1(1) THEN RETURN;
   DO I=1 to M; T(I)=A(I); END;
   CALL MERGE(T,M,AMP1,N-M,A);
   RETURN;
END MERGESORT;

Pop11

Pop11 library function sorts lists. So we first convert array to list, then sort and finally convert back:

lvars ar = {2 4 3 1 2};
;;; Convert array to list.
;;; destvector leaves its results and on the pop11 stack + an integer saying how many there were
destvector(ar);
;;; conslist uses the items left on the stack plus the integer, to make a list of those items.
lvars ls = conslist();
;;; Sort it
sort(ls) -> ls;
;;; Convert list to array
destlist(ls);
consvector() -> ar;

The above can be abbreviated to more economical, but possibly more opaque, syntax, using pop11 as a functional language:

lvars ar = {2 4 3 1 2};
consvector(destlist(sort(conslist(destvector(ar))))) -> ar;
;;; print the sorted vector:
ar =>
** {1 2 2 3 4}

(The list created by conslist will be garbage-collected.)

Alternatively, using the datalist function, even more economically:

lvars ar = {2 4 3 1 2};
consvector(destlist(sort(datalist(ar)))) -> ar;


or in Forth-like pop11 postfix syntax:

lvars ar = {2 4 3 1 2};
ar.datalist.sort.destlist.consvector -> ar;

Potion

(7, 5, 1, 2, 3, 8, 9) sort join(", ") print

PowerBASIC

PowerBASIC has several options available for sorting. At its simplest, an array (of any type) is sorted using ARRAY SORT:

ARRAY SORT x()

Options are available to limit sorting to only part of the array, collate string arrays, sort multiple arrays together, etc. (Details here.)

PowerShell

34,12,23,56,1,129,4,2,73 | Sort-Object

Prolog

 ?- msort([10,5,13,3, 85,3,1], L).
L = [1,3,3,5,10,13,85].

Note that sort/2 removes duplicates.

PureBasic

Dim numbers(20)
For i = 0 To 20
   numbers(i) = Random(1000)
Next

SortArray(numbers(), #PB_Sort_Ascending)

Python

Works with: Python version 2.3
nums = [2,4,3,1,2]
nums.sort()

Note: The array nums is sorted in place.

Interpreter: Python 2.4 (and above)

You could also use the built-in sorted() function

nums = sorted([2,4,3,1,2])

Quackery

As a dialogue in the Quackery shell.

/O> [] 20 times [ 10 random join ] 
... dup echo cr
... sort
... echo cr 
... 
[ 5 2 5 0 4 5 1 5 1 1 0 3 7 2 0 9 6 1 8 7 ]
[ 0 0 0 1 1 1 1 2 2 3 4 5 5 5 5 6 7 7 8 9 ]

R

nums <- c(2,4,3,1,2)
sorted <- sort(nums)

Racket

-> (sort '(1 9 2 8 3 7 4 6 5) <)
'(1 2 3 4 5 6 7 8 9)

Raku

(formerly Perl 6) If @a contains only numbers:

my @sorted = sort @a;

For an in-place sort:

@a .= sort;

Rascal

Rascal has a built-in sort function that sort the elements of a list. Additionally, one can give a LessThenOrEqual function to compare the elements (See documentation).

rascal>import List;
ok

rascal>a = [1, 4, 2, 3, 5];
list[int]: [1,4,2,3,5]

rascal>sort(a)
list[int]: [1,2,3,4,5]

rascal>sort(a, bool(int a, int b){return a >= b;})
list[int]: [5,4,3,2,1]

Raven

Sort list in place:

[ 2 4 3 1 2 ] sort

REBOL

sort [2 4 3 1 2]

Red

>> nums: [3 2 6 4 1 9 0 5 7]
== [3 2 6 4 1 9 0 5 7]
>> sort nums
== [0 1 2 3 4 5 6 7 9]

REXX

sort an array

This REXX version creates an array with over a score of Euler numbers (integers), then sorts it.

/*REXX program sorts an array (using E─sort), in this case, the array contains integers.*/
numeric digits 30                                /*enables handling larger Euler numbers*/
                          @.  =              0;            @.1 =               1
                          @.3 =             -1;            @.5 =               5
                          @.7 =            -61;            @.9 =            1385
                          @.11=         -50521;            @.13=         2702765
                          @.15=     -199360981;            @.17=     19391512145
                          @.19= -2404879675441;            @.21= 370371188237525
#= 21                                            /*indicate there're  21 Euler  numbers.*/
call tell  'unsorted'                            /*display the array before the  eSort. */
call eSort     #                                 /*sort the array of some Euler numbers.*/
call tell  '  sorted'                            /*display the array  after  the eSort. */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
eSort: procedure expose @.;   parse arg N;     h=N                   /*an eXchange sort.*/
              do  while h>1;                   h= h%2                /*define a segment.*/
                 do i=1  for N-h;              j=i;     k= h+i       /*sort top segment.*/
                    do  while  @.k<@.j                               /*see if need swap.*/
                        parse value  @.j @.k   with   @.k @.j        /*swap two elements*/
                        if h>=j  then leave;   j= j-h;   k= k-h      /*this part sorted?*/
                        end   /*while @.k<@.j*/
                    end       /*i*/
              end             /*while h>1*/
       return
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell:  say copies('─', 65);       _= left('',9);                       w= length(#)
              do j=1  for #;  say _ arg(1)  'array element'   right(j, w)"="right(@.j, 20)
              end   /*j*/
       return
output   when using the default internal input:
─────────────────────────────────────────────────────────────────
          unsorted array element  1=                   1
          unsorted array element  2=                   0
          unsorted array element  3=                  -1
          unsorted array element  4=                   0
          unsorted array element  5=                   5
          unsorted array element  6=                   0
          unsorted array element  7=                 -61
          unsorted array element  8=                   0
          unsorted array element  9=                1385
          unsorted array element 10=                   0
          unsorted array element 11=              -50521
          unsorted array element 12=                   0
          unsorted array element 13=             2702765
          unsorted array element 14=                   0
          unsorted array element 15=          -199360981
          unsorted array element 16=                   0
          unsorted array element 17=         19391512145
          unsorted array element 18=                   0
          unsorted array element 19=      -2404879675441
          unsorted array element 20=                   0
          unsorted array element 21=     370371188237525
─────────────────────────────────────────────────────────────────
            sorted array element  1=      -2404879675441
            sorted array element  2=          -199360981
            sorted array element  3=              -50521
            sorted array element  4=                 -61
            sorted array element  5=                  -1
            sorted array element  6=                   0
            sorted array element  7=                   0
            sorted array element  8=                   0
            sorted array element  9=                   0
            sorted array element 10=                   0
            sorted array element 11=                   0
            sorted array element 12=                   0
            sorted array element 13=                   0
            sorted array element 14=                   0
            sorted array element 15=                   0
            sorted array element 16=                   1
            sorted array element 17=                   5
            sorted array element 18=                1385
            sorted array element 19=             2702765
            sorted array element 20=         19391512145
            sorted array element 21=     370371188237525

sort a list

This REXX version creates a list with a bunch of interesting integers, then sorts it.

Because it so much more efficient to sort an array,   an array is built from the list,
it is then sorted,   and then the list is re-constituted.

/*REXX program sorts  (using E─sort)  and displays a list of some interesting integers. */
  Bell=  1 1 2 5 15 52 203 877 4140 21147 115975           /*a few  Bell          "     */
  Bern= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617'      /*"  "   Bernoulli     "     */
Perrin=  3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90        /*"  "   Perrin        "     */
  list= Bell  Bern  Perrin                                 /*throw them all ───► a pot. */
say 'unsorted =' list                                      /*display what's being shown.*/
#= words(list)                                             /*nice to have # of elements.*/
                              do j=1  for #                /*build an array, a single   */
                              @.j=word(list, j)            /*     ··· element at a time.*/
                              end    /*j*/
call eSort #                                               /*sort the collection of #s. */
$=;                           do k=1  for #;   $= $ @.k    /*build a list from the array*/
                              end    /*k*/
say '  sorted =' space($)                                  /*display the sorted list.   */
exit                                              /*stick a fork in it,  we're all done.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
eSort: procedure expose @.;   parse arg N;       h= N                /*an eXchange sort.*/
              do  while h>1;                     h= h % 2            /*define a segment.*/
                do i=1  for N-h;                 j= i;      k= h + i /*sort top segment.*/
                  do  while  @.k<@.j                                 /*see if need swap.*/
                  parse value  @.j  @.k   with   @.k  @.j            /*swap two elements*/
                  if h>=j  then leave;           j= j - h;  k= k - h /*this part sorted?*/
                  end   /*while @.k<@.j*/
                end     /*i*/
              end       /*while h>1*/
       return
output   when using the default internal inputs:

(Shown at   5/6   size.)

unsorted = 1 1 2 5 15 52 203 877 4140 21147 115975 1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90
  sorted = -3617 -691 -1 -1 -1 0 0 0 0 0 0 0 0 1 1 1 1 1 2 2 2 3 3 5 5 5 5 7 7 10 12 15 17 22 29 39 51 52 68 90 203 877 4140 21147 115975

Ring

aArray = [2,4,3,1,2]
see sort(aArray)

RPL

Works with: HP version 48G
{2 4 3 1 2} SORT
Output:
1: { 1 2 2 3 4 }

Ruby

nums = [2,4,3,1,2]
sorted = nums.sort      # returns a new sorted array.  'nums' is unchanged
p sorted                #=> [1, 2, 2, 3, 4]
p nums                  #=> [2, 4, 3, 1, 2]

nums.sort!              # sort 'nums' "in-place"
p nums                  #=> [1, 2, 2, 3, 4]

Rust

Uses merge sort in place (undocumented), allocating ~2*n memory where n is a length of an array.

fn main() {
    let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);

    a.sort();
    println!("{:?}", a);
}

Sather

class MAIN is
   main is
      arr: ARRAY{INT} := |4, 6, 7, 2, 1, 0, 100, 21, 34|;
      #OUT+"unsorted: " + arr + "\n";

      -- sort in place:
      arr.sort;

      #OUT+"  sorted: " + arr + "\n";
   end;
end;

Output:

unsorted: {4,6,7,2,1,0,100,21,34}
  sorted: {0,1,2,4,6,7,21,34,100}

Scala

Library: Scala

Array

Scala's "default" Array is a mutable data structure, very close to Java's Array. Generally speaking, that means an "array" is not very Scala-lesque, even as mutable data structures go. It can serves a purpose, though. If array is the right data type for your need, then that is how you sort it.

import scala.compat.Platform

object Sort_an_integer_array extends App {
  val array = Array((for (i <- 0 to 10) yield scala.util.Random.nextInt()):
    _* /*Sequence is passed as multiple parameters to Array(xs : T*)*/)

  /** Function test the array if it is in order */
  def isSorted[T](arr: Array[T]) = array.sliding(2).forall(pair => pair(0) <= pair(1))

  assert(!isSorted(array), "Not random")
  scala.util.Sorting.quickSort(array)
  assert(isSorted(array), "Not sorted")

  println(s"Array in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}

List

println(List(5,2,78,2,578,-42).sorted)
//--> List(-42, 2, 2, 5, 78, 578)

Scheme

Works with: Guile

Same as Common Lisp

(sort #(9 -2 1 2 8 0 1 2) #'<)
Library: Scheme/SRFIs

Sorting is also available through SRFIs. SRFI 132 provides separate list-sort and vector-sort routines:

> (import (srfi 132))
> (list-sort < '(9 -2 1 2 8 0 1 2))
(-2 0 1 1 2 2 8 9)

> (vector-sort < #(9 -2 1 2 8 0 1 2))
#(-2 0 1 1 2 2 8 9)

SRFI 132 replaced the older SRFI 95, which is still found in many implementations. SRFI 95 provides a generic sort function (but note the order of the sequence and comparator!):

> (import (srfi 95))
> (sort '(9 -2 1 2 8 0 1 2) <)
(-2 0 1 1 2 2 8 9)
> (sort #(9 -2 1 2 8 0 1 2) <)
#(-2 0 1 1 2 2 8 9)

Seed7

var array integer: nums is [] (2, 4, 3, 1, 2);

nums := sort(nums);

Sidef

var nums = [2,4,3,1,2];
var sorted = nums.sort;  # returns a new sorted array.
nums.sort!;              # sort 'nums' "in-place"

Slate

 #(7 5 2 9 0 -1) sort

Smalltalk

 #(7 5 2 9 0 -1) asSortedCollection

or destructive:

 #(7 5 2 9 0 -1) sort

SparForte

As a structured script.

#!/usr/local/bin/spar
pragma annotate( summary, "int_sort" )
              @( description, "Sort an array (or list) of integers in ascending" )
              @( description, "numerical order. Use a sorting facility provided by" )
              @( description, "the language/library if possible." )
              @( category, "tutorials" )
              @( author, "Ken O. Burtch" )
              @( see_also, "http://rosettacode.org/wiki/Sort_an_integer_array" );
pragma license( unrestricted );

pragma software_model( nonstandard );
pragma restriction( no_external_commands );

procedure int_sort is
  type int_array is array (1..9) of integer;
  int_values : int_array := (0,1,8,2,7,3,6,4,5);
begin
  arrays.heap_sort( int_values );
  for i in arrays.first( int_values )..arrays.last( int_values ) loop
    ? int_values(i);
  end loop;
end int_sort;

Sparkling

var arr = { 2, 8, 1, 4, 6, 5, 3, 7, 0, 9 };
sort(arr);

Standard ML

The Standard ML Basis library does not have any sorting facilities. But each implementation of Standard ML has its own.

Array

Works with: SML/NJ
- val nums = Array.fromList [2, 4, 3, 1, 2];
val nums = [|2,4,3,1,2|] : int array
- ArrayQSort.sort Int.compare nums;
val it = () : unit
- nums;
val it = [|1,2,2,3,4|] : int array
Works with: Moscow ML
- load "Arraysort";
> val it = () : unit
- load "Int";
> val it = () : unit
- val nums = Array.fromList [2, 4, 3, 1, 2];
> val nums = <array> : int array
- Arraysort.sort Int.compare nums;
> val it = () : unit
- Array.foldr op:: [] nums;
> val it = [1, 2, 2, 3, 4] : int list

List

Works with: SML/NJ
- val nums = [2, 4, 3, 1, 2];
val nums = [2,4,3,1,2] : int list
- val sorted = ListMergeSort.sort op> nums;
val sorted = [1,2,2,3,4] : int list
Works with: Moscow ML
- load "Listsort";
> val it = () : unit
- load "Int";
> val it = () : unit
- val nums = [2, 4, 3, 1, 2];
> val nums = [2, 4, 3, 1, 2] : int list
- val sorted = Listsort.sort Int.compare nums;
> val sorted = [1, 2, 2, 3, 4] : int list

Stata

Sort a Stata dataset

See sort in Stata help.

. clear
. matrix a=(2,9,4,7,5,3,6,1,8)'
. qui svmat a
. sort a
. list

     +----+
     | a1 |
     |----|
  1. |  1 |
  2. |  2 |
  3. |  3 |
  4. |  4 |
  5. |  5 |
     |----|
  6. |  6 |
  7. |  7 |
  8. |  8 |
  9. |  9 |
     +----+

Sort a macro list

See macrolists in Stata help for other functions on lists stored in macros.

. local a 2 9 4 7 5 3 6 1 8
. di "`: list sort a'"
1 2 3 4 5 6 7 8 9

Mata

See Mata's sort function.

mata
: a=2\9\4\7\5\3\6\1\8

: sort(a,1)
       1
    +-----+
  1 |  1  |
  2 |  2  |
  3 |  3  |
  4 |  4  |
  5 |  5  |
  6 |  6  |
  7 |  7  |
  8 |  8  |
  9 |  9  |
    +-----+
end

Swift

Sort in place

Works with: Swift version 2.x+
var nums = [2, 4, 3, 1, 2]
nums.sortInPlace()
print(nums)

or

var nums = [2, 4, 3, 1, 2]
nums.sortInPlace(<)
print(nums)
Works with: Swift version 1.x
var nums = [2, 4, 3, 1, 2]
nums.sort(<)
println(nums)

or

var nums = [2, 4, 3, 1, 2]
sort(&nums)
println(nums)

or

var nums = [2, 4, 3, 1, 2]
sort(&nums, <)
println(nums)

Return new array

You could also create a new sorted array without affecting the original one:

Works with: Swift version 2.x+
let nums = [2,4,3,1,2].sort()
print(nums)

or

let nums = [2,4,3,1,2].sort(<)
print(nums)
Works with: Swift version 1.x
let nums = sorted([2,4,3,1,2])
println(nums)

or

let nums = [2,4,3,1,2].sorted(<)
println(nums)

Tcl

set result [lsort -integer $unsorted_list]

TI-83 BASIC

Store input into L1, run prgmSORTBTIN, and L2 will be L1, only sorted.

:L1→L2
:SortA(L2)

SortA is found via: [LIST] → ENTER. SortD is also available for a descending sort.

Toka

This can be done by using the bubble sort library:

needs bsort
arrayname number_elements bsort

See the Toka entry on Bubble Sort for a full example.

UNIX Shell

Each shell parameter separates the integers using the default IFS whitespace (space, tab, newline).

nums="2 4 3 1 5"
sorted=`printf "%s\n" $nums | sort -n`
echo $sorted  # prints 1 2 3 4 5

Alternate solution: sorted=`for i in $nums; do echo $i; done | sort -n`


Some shells have real arrays. You still need IFS to split the string from sort -n to an array.

Works with: pdksh version 5.2.14
set -A nums 2 4 3 1 5
set -A sorted $(printf "%s\n" ${nums[*]} | sort -n)
echo ${sorted[*]}  # prints 1 2 3 4 5

Users of bash, ksh93 and mksh can probably use the nums=(2 4 3 1 2) syntax.

Ursa

decl int<> nums
append 2 4 3 1 2 nums
sort nums

Ursala

using the built in sort operator, -<, with the nleq library function for comparing natural numbers

#import nat

#cast %nL

example = nleq-< <39,47,40,53,14,23,88,52,78,62,41,92,88,66,5,40>

output:

<5,14,23,39,40,40,41,47,52,53,62,66,78,88,88,92>

V (Vlang)

fn main() {
   mut nums := [3, 2, 4, 1, 6, 7, 5, 0]
   nums.sort()
   println(nums)
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7]

WDTE

let a => import 'arrays';
a.sort [39; 47; 40; 53; 14; 23; 88; 52; 78; 62; 41; 92; 88; 66; 5; 40] < -- io.writeln io.stdout;

Wortel

@sort [39 47 40 53 14 23 88 52 78 62 41 92 88 66 5 40]

Wren

Library: Wren-sort
import "./sort" for Sort

var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5]
Sort.quick(a)
System.print(a)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

XPL0

include c:\cxpl\codes;          \intrinsic 'code' declarations

proc    SSort(A, N);            \Shell sort array in ascending order
int     A;                      \address of array
int     N;                      \number of elements in array (size)
int     I, J, Gap, JG, T;
[Gap:= N>>1;
while Gap > 0 do
        [for I:= Gap to N-1 do
                [J:= I - Gap;
                loop    [JG:= J + Gap;
                        if A(J) <= A(JG) then quit;
                        T:= A(J);   A(J):= A(JG);   A(JG):= T;  \swap elements
                        J:= J - Gap;
                        if J < 0 then quit;
                        ];
                ];
        Gap:= Gap>>1;
        ];
];      \SSort

int A, I;
[A:= [3, 1, 4, 1, 5, 9, 2, 6, 5, 4];
SSort(A, 10);
for I:= 0 to 10-1 do [IntOut(0, A(I));  ChOut(0, ^ )];
CrLf(0);
]

Output:

1 1 2 3 4 4 5 5 6 9 

Yabasic

export sub shell_sort(x())
// Shell sort based on insertion sort

   local gap, i, j, first, last, tempi, tempj

   last = arraysize(x(),1)
   gap = int(last / 10) + 1
   while(TRUE)
	first = gap + 1
	for i = first to last
	   	tempi = x(i)
	    	j = i - gap
	    	while(TRUE)
			tempj = x(j)
			if tempi >= tempj then
		    		j = j + gap
		    		break
			end if
			x(j+gap) = tempj
			if j <= gap then
		    		break
			end if
			j = j - gap
	    	wend
	    	x(j) = tempi
	next i
	if gap = 1 then
	   	return
	else
	   	gap = int(gap / 3.5) + 1
	end if
   wend
end sub

if peek$("library") = "main" then

	clear screen
	
	ITEMS = 100
	dim numeros(ITEMS)
	
	for n = 1 to ITEMS
		numeros(n) = ran(ITEMS + 1)
	next n
	
	print time$
	shell_sort(numeros())
	print time$
	print "Press a key to see ordered numbers."
	inkey$
	
	for n = 1 to ITEMS
		print numeros(n),", ";
	next n

end if

Yorick

In Yorick, sort returns an index list into the array that will put it in sorted order.

nums = [2,4,3,1,2];
nums = nums(sort(nums));

zkl

In place sorting read/write list:

a:=L(4,5,2,6); a.sort(); a.println() //--> L(2,4,5,6)

Sort a read only list:

a:=T(4,5,2,6); b:=a.sort();
b.println(); //--> L(2,4,5,6)
a.println(); //--> L(4,5,2,6)

Zoea

program: sort_integer_array
  input: [2,4,3,1]
  output: [1,2,3,4]

Zoea Visual

Sort integer array