Sort an integer array: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Wren}}: Minor tidy) |
|||
(8 intermediate revisions by 7 users not shown) | |||
Line 12:
{{trans|Python}}
<
nums.sort()</
You could also use the built-in sorted() function:
<
=={{header|4D}}==
===English===
<
APPEND TO ARRAY($nums;2)
APPEND TO ARRAY($nums;4)
Line 27:
APPEND TO ARRAY($nums;2)
SORT ARRAY($nums) ` sort in ascending order
SORT ARRAY($nums;<) ` sort in descending order</
===Français===
<
AJOUTER A TABLEAU($nombres;2)
AJOUTER A TABLEAU($nombres;4)
Line 38:
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</
=={{header|8th}}==
<
[ 10,2,100 ] ' n:cmp a:sort . cr
</syntaxhighlight>
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 */
Line 213:
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
PROC PrintArray(INT ARRAY a INT size)
Line 255:
Test(c,8,ASCENDING)
Test(d,12,ASCENDING)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_an_integer_array.png Screenshot from Atari 8-bit computer]
Line 281:
=={{header|ActionScript}}==
<
function compare(x:int, y:int):Number
{
Line 287:
}
var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]);
nums.sort(compare);</
=={{header|Ada}}==
{{works with|GNAT|GPL 2006}}
<
procedure Integer_Sort is
Line 333:
begin
Sort(Values);
end Integer_Sort;</
=={{header|ALGOL 68}}==
Line 341:
{{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}}
<
MODE TYPE = INT;
Line 364:
in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq);
print((shell sort((2, 4, 3, 1, 2)), new line))</
Output:
<pre>
Line 372:
=={{header|ALGOL W}}==
Algol W doesn't have standard sorting facilities. This uses the Algol W quicksort sample in 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 %
Line 387:
for i := 1 until 5 do writeon( i_w := 1, s_w := 1, t( i ) )
end
end.</
{{out}}
<pre>
Line 395:
=={{header|APL}}==
{{works with|APL2}}
<
X[⍋X]
15 36 39 43 51 63 69 89 92 92</
=={{header|AppleScript}}==
Line 409:
for which AppleScript was presumably designed.
<
-- sort :: [a] -> [a]
Line 451:
end script
end if
end mReturn</
{{Out}}
<pre>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9},
Line 458:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 616:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
=={{header|Arturo}}==
<
sort 'arr ; in-place
loop arr => print</
{{out}}
Line 637:
=={{header|AutoHotkey}}==
<
sort, numbers, N D%A_Space%
Msgbox % numbers</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SORT_AN_INTEGER_ARRAY.AWK
BEGIN {
Line 658:
printf("\t%s\n",description)
}
</syntaxhighlight>
<p>output:</p>
<pre>
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.
<
4→{L₁+1}
3→{L₁+2}
Line 675:
2→{L₁+4}
SortD(L₁,5)</
=={{header|Babel}}==
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.
<
( 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> {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:
<
( 90 89 88 86 83 83 75 73 68 67 63 54 53 49 46 34 28 21 20 9 )</
=={{header|BaCon}}==
<
DECLARE values[5] TYPE NUMBER
values[0] = 23
Line 713:
PRINT values[i], ", ";
NEXT
PRINT values[4]</
{{out}}
Line 723:
{{works with|BBC BASIC for Windows}}
Uses the supplied SORTLIB library.
<
sort% = FN_sortinit(0,0)
Line 735:
PRINT ; array(i%) ", ";
NEXT
PRINT ; array(i%)</
Output:
<pre>
Line 742:
=={{header|Beads}}==
<
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</
=={{header|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.
<syntaxhighlight lang="befunge">v
> 543** > :#v_ $&> :#v_ 1 > :0g > :#v_ $ 1+: 543** `! #v_ 25*,@
^-1p0\0:< ^-1 p0\+1 g0:&< ^-1\.:\<
^ <</
=={{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}}==
Line 769 ⟶ 774:
{!} 21</pre>
To complete the task need to unfold the terms with a numerical factor >1:
<
(sort=
sum elem sorted n
Line 785 ⟶ 790:
& !sorted);
out$sort$(9 -2 1 2 8 0 1 2);</
{{out}}
<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.
Line 792 ⟶ 797:
=={{header|Burlesque}}==
<
=={{header|C}}==
<
#include <stdio.h> /* printf() */
Line 811 ⟶ 816:
nums[0], nums[1], nums[2], nums[3], nums[4]);
return 0;
}</
''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 817 ⟶ 822:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
Line 825 ⟶ 830:
Array.Sort(unsorted);
}
}</
=={{header|C++}}==
Line 831 ⟶ 836:
===Simple Array===
<
int main()
Line 838 ⟶ 843:
std::sort(nums, nums+sizeof(nums)/sizeof(int));
return 0;
}</
===<tt>std::vector</tt>===
<
#include <vector>
Line 854 ⟶ 859:
std::sort(nums.begin(), nums.end());
return 0;
}</
===<tt>std::list</tt>===
<
int main()
Line 869 ⟶ 874:
nums.sort();
return 0;
}</
=={{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.
<
sortArray :: (a e) -> a e | Array a e & Ord e
Line 879 ⟶ 884:
Start :: {#Int}
Start = sortArray {2, 4, 3, 1, 2}</
=={{header|Clojure}}==
<
(1 2 3 4 5)</
=={{header|COBOL}}==
{{works with|Visual COBOL}}
<
DATA DIVISION.
Line 908 ⟶ 913:
END-PERFORM
DISPLAY SPACE
.</
=={{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:
<
#(-2 0 1 1 2 2 8 9)</
=={{header|Crystal}}==
Example demonstrating the support for copy sort and in-place sort (like Ruby)
<syntaxhighlight lang="ruby">
a = [5, 4, 3, 2, 1]
puts a.sort
Line 928 ⟶ 933:
puts a
# => [1, 2, 3, 4, 5]
</syntaxhighlight>
=={{header|D}}==
<
void main() {
Line 937 ⟶ 942:
data.sort(); // in-place
assert(data == [1, 2, 2, 3, 4]);
}</
=={{header|Delphi}}==
<
var
Line 947 ⟶ 952:
a := TIntegerDynArray.Create(5, 4, 3, 2, 1);
TArray.Sort<Integer>(a);
end;</
=={{header|DWScript}}==
<
a.Sort; // ascending natural sort
PrintLn(a.Map(IntToStr).Join(',')); // 1,2,3,4,5</
=={{header|Déjà Vu}}==
<
{{out}}
<pre>[ 1 2 3 4 5 ]</pre>
=={{header|E}}==
<
=={{header|EGL}}==
{{works with|EDT}}
The following works in EDT with Rich UI and stand-alone programs.
<
function main()
Line 980 ⟶ 985:
end
end</
{{works with|RBD}}
The following works in RBD but only with Rich UI programs.
<
RUILib.sort(test1, sortFunction);
Line 989 ⟶ 994:
function sortFunction(a any in, b any in) returns (int)
return ((a as int) - (b as int));
end</
=={{header|Eiffel}}==
Line 998 ⟶ 1,003:
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]
Line 1,004 ⟶ 1,009:
create l_array.make_from_iterable (<<9,8,7,6,5,4,3,2,1,0>>)
end
</syntaxhighlight>
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions;
Line 1,016 ⟶ 1,021:
console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable())
}</
=={{header|Elixir}}==
<
IO.inspect Enum.sort(list)
IO.inspect Enum.sort(list, &(&1>&2))</
{{out}}
Line 1,030 ⟶ 1,035:
=={{header|Erlang}}==
<
SortedList = lists:sort(List).</
=={{header|Euphoria}}==
<
print(1,sort({20, 7, 65, 10, 3, 0, 8, -60}))</
=={{header|F_Sharp|F#}}==
<
let nums = [| 2; 4; 3; 1; 2 |]
Array.sortInPlace nums
Line 1,044 ⟶ 1,049:
// create a sorted copy of a list
let nums2 = [2; 4; 3; 1; 2]
let sorted = List.sort nums2</
=={{header|Factor}}==
<
=={{header|Fantom}}==
Line 1,065 ⟶ 1,070:
{{works with|Win32Forth|4.2}}
===Win32Forth===
<
test-data 5 cell-sort
</syntaxhighlight>
===ANS/ISO Forth===
{{works with|GForth}}
Line 1,073 ⟶ 1,078:
Standard Forth does not have a library sort
<
CREATE MYARRAY SIZE CELLS ALLOT
Line 1,115 ⟶ 1,120:
DUP 2 < IF 2DROP EXIT THEN 1- CELLS OVER + QSORT ;</LANG>
Test at the console
<
MYARRAY SIZE QUICKSORT ok</
=={{header|Fortran}}==
{{works with|Silverfrost FTN95}}
<
! n = number of elements
! a = array to be sorted
! b = array of indices of a. b(1) 'points' to the minimum value etc.</
=={{header|FreeBASIC}}==
Qsort is not buildin, but include in the compiler package.
<
' compile with: fbc -s console
Line 1,184 ⟶ 1,189:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>unsorted array
Line 1,194 ⟶ 1,199:
=={{header|Frink}}==
The following sorts an array in-place.
<
sort[a]</
=={{header|FunL}}==
<
println( sort(nums) ) // sort in ascending order
println( nums.sortWith((>)) ) // sort in descending order</
{{out}}
Line 1,207 ⟶ 1,212:
[-42, 2, 2, 5, 78, 578]
[578, 78, 5, 2, 2, -42]
</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}}==
'''[https://gambas-playground.proko.eu/?gist=1f1d244aa95c329eb87cb538f0d5fc4a Click this link to run this code]'''
<
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Line 1,230 ⟶ 1,256:
Print Left(sOutput, -2)
End</
Output:
Line 1,238 ⟶ 1,264:
=={{header|GAP}}==
<
# Make a copy (with "b := a;", b and a would point to the same list)
b := ShallowCopy(a);
Line 1,251 ⟶ 1,277:
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
b;
# [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ]</
=={{header|Go}}==
<
import "fmt"
import "sort"
Line 1,262 ⟶ 1,288:
sort.Ints(nums)
fmt.Println(nums)
}</
=={{header|Golfscript}}==
<
=={{header|Groovy}}==
<
Output:
Line 1,276 ⟶ 1,302:
{{works with|GHC|GHCi|6.6}}
<
sorted = List.sort nums</
=={{header|HicEst}}==
<
array = INT( RAN(100) )
SORT(Vector=array, Sorted=array) </
=={{header|Huginn}}==
<
nums = [2, 4, 3, 1, 2];
nums.sort();
}</
=={{header|Icon}} and {{header|Unicon}}==
Line 1,295 ⟶ 1,321:
In the example below, L will remain an unsorted list and S will be sorted.
<
=={{header|IDL}}==
<
=={{header|Inform 7}}==
<
sort L;</
=={{header|Io}}==
<
sorted := nums sort # returns a new sorted array. 'nums' is unchanged
nums sortInPlace # sort 'nums' "in-place"</
=={{header|J}}==
<syntaxhighlight lang
The verb<tt> /:~ </tt>sorts <i>anything</i> that J can represent. For example:
<
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 <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.
Line 1,323 ⟶ 1,349:
=={{header|Java}}==
===Array===
<
public class Example {
Line 1,331 ⟶ 1,357:
Arrays.sort(nums);
}
}</
===List===
{{works with|Java|1.5+}}
<
import java.util.Collections;
import java.util.List;
Line 1,345 ⟶ 1,371:
Collections.sort(nums);
}
}</
=={{header|JavaScript}}==
Line 1,352 ⟶ 1,378:
JavaScript sorts lexically by default, so "10000" comes before "2". To sort numerically, a custom comparator is used.
<
return a - b;
}
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
numbers.sort(int_arr);
document.write(numbers);</
=={{header|Jinja}}==
<
from jinja2 import Template
print(Template("{{ [53, 17, 42, 61, 35] | sort }}").render())
</syntaxhighlight>
Descending order:
<
from jinja2 import Template
print(Template("{{ [53, 17, 42, 61, 35] | sort(reverse=true) }}").render())
</syntaxhighlight>
=={{header|jq}}==
jq's builtin <code>sort</code> filter sorts the elements of an array in ascending order:
<
=={{header|Julia}}==
Julia has both out-of-place (<code>sort</code>) and in-place (<code>sort!</code>) sorting functions in its standard-library:
<
4-element Int32 Array:
4
Line 1,408 ⟶ 1,434:
2
3
4</
=={{header|K}}==
<
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</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,425 ⟶ 1,451:
ints.sort()
println(ints.joinToString(prefix = "[", postfix = "]"))
}</
{{out}}
Line 1,433 ⟶ 1,459:
=={{header|Lambdatalk}}==
<
1) sorting digits in a number returns a new number of ordered digits
{W.sort < 51324}
Line 1,445 ⟶ 1,471:
{A.sort! < {A.new 51 111 33 2 41}}
-> [2,33,41,51,111]
</syntaxhighlight>
=={{header|Lasso}}==
<
#array->sort
#array // 1, 2, 3, 4, 5, 6, 20
Line 1,454 ⟶ 1,480:
// Reverse the sort order
#array->sort(false)
#array // 20, 6, 5, 4, 3, 2, 1</
=={{header|Liberty BASIC}}==
LB has an array-sort command. Parameters are arrayname, start term, finish term.
<
dim IntArray( N)
Line 1,473 ⟶ 1,499:
for i =1 to N
print IntArray( i)
next i</
=={{header|Lingo}}==
<
l.sort()
put l
-- [4, 7, 23]</
=={{header|LiveCode}}==
LiveCode can sort lines or items natively. The delimiter for items can be set to any single character, but defaults to comma.
<
sort items of X numeric
put X
-- outputs "1,2,3,4,5"</
=={{header|Lua}}==
<
table.sort(t)
print(unpack(t))</
=={{header|Maple}}==
<
sort(Array([5,7,8,3,6,1]))</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|MATLAB}}==
<
[b,idx] = sort(a) % b contains a(idx)</
=={{header|Maxima}}==
<
=={{header|MAXScript}}==
<
arr = sort arr</
=={{header|Mercury}}==
<syntaxhighlight lang="text">:- module sort_int_list.
:- interface.
:- import_module io.
Line 1,525 ⟶ 1,551:
list.sort(Nums, Sorted),
io.write(Sorted, !IO),
io.nl(!IO).</
=={{header|min}}==
{{works with|min|0.19.3}}
<
{{out}}
<pre>
Line 1,537 ⟶ 1,563:
=={{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>.
<
IMPORT IntArraySort;
Line 1,545 ⟶ 1,571:
BEGIN
IntArraySort.Sort(arr);
END ArraySort.</
=={{header|MUMPS}}==
<
;X is the list of items to sort
;X1 is the temporary array
Line 1,559 ⟶ 1,585:
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:<pre>USER>W $$SORTARRAY^ROSETTA("3,5,1,99,27,16,0,-1",",")
-1,0,1,3,5,16,27,99
Line 1,566 ⟶ 1,592:
=={{header|Nanoquery}}==
'sort' in the Nanoquery standard library has a Quicksort function.
<
% println sort({2,4,3,1,2})
[1, 2, 2, 3, 4]</
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<doc><h2>Sort integer array, in Neko</h2>
<p>Array sort function modified from Haxe codegen with -D neko-source</p>
Line 1,610 ⟶ 1,636:
/* Also returns the sorted array for chaining */
$print(sort($array(3,1,4,1,5,9,2,6,5,3,5,8)), "\n")</
{{out}}
Line 1,620 ⟶ 1,646:
=={{header|Nemerle}}==
<
module IntSort
Line 1,632 ⟶ 1,658:
WriteLine(sorted);
}
}</
Output:
<pre>[1, 5, 3, 7, 2, 8, 3, 9]
Line 1,638 ⟶ 1,664:
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols binary
Line 1,659 ⟶ 1,685:
say sorted.strip('t')
return</
'''Output'''
Line 1,669 ⟶ 1,695:
NetRexx reimplementations of the [[#REXX|Rexx]] samples from below:
<
options replace format comments java crossref savelog symbols
Line 1,740 ⟶ 1,766:
say
return</
'''Output'''
Line 1,791 ⟶ 1,817:
</pre>
<
options replace format comments java crossref savelog symbols
Line 1,844 ⟶ 1,870:
end
return</
'''Output'''
Line 1,853 ⟶ 1,879:
=={{header|Nial}}==
<
= 10 9 8 7 6 1</
=={{header|Nim}}==
<
var a: array[0..8, int] = [2, 3, 5, 8, 4, 1, 6, 9, 7]
a.sort(Ascending)
for x in a:
echo x</
{{out}}
<pre>1
Line 1,876 ⟶ 1,902:
=={{header|Niue}}==
'''Library'''
<
0 1 2 3 6 8</
=={{header|Objeck}}==
<
class Sort {
function : Main(args : System.String[]) ~ Nil {
Line 1,887 ⟶ 1,913:
}
}
}</
=={{header|Objective-C}}==
<
NSArray *sorted = [nums sortedArrayUsingSelector:@selector(compare:)];</
=={{header|OCaml}}==
===Array===
<
Array.sort compare nums</
===List===
<
let sorted = List.sort compare nums</
=={{header|Octave}}==
Line 1,906 ⟶ 1,932:
The variable <tt>v</tt> can be a vector or a matrix (columns will be sorted).
<
=={{header|Oforth}}==
<
=={{header|ooRexx}}==
<
say "The sorted numbers are"
say a~sortWith(.numericComparator~new)~makeString</
Output:
<pre>
Line 1,929 ⟶ 1,955:
=={{header|Order}}==
Passing the less-than operator to the built-in sequence (i.e. list) sort function:
<
ORDER_PP( 8seq_sort(8less, 8seq(2, 4, 3, 1, 2)) )</
=={{header|Oz}}==
<
Nums = [2 4 3 1 2]
Sorted = {List.sort Nums Value.'<'}
in
{Show Sorted}</
=={{header|PARI/GP}}==
<syntaxhighlight lang
=={{header|Peloton}}==
Sorting a list of numbers as strings and as numbers (from the manual.)
<
<@ LETCNSLSTLIT>L|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@>
Numbers sort as strings
Line 1,959 ⟶ 1,985:
<@ SAYDMPLST>list</@>
<@ ACTSRTENTLSTLIT>list|__NumericDescending</@>
<@ SAYDMPLST>list</@></
Output
<
Numbers sort as strings
Line 1,976 ⟶ 2,002:
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^</
=={{header|Perl}}==
{{works with|Perl|5.8.6}}
<
@sorted = sort {$a <=> $b} @nums;</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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>
<!--</
=={{header|Phixmonti}}==
<
( 9 10 3 1 4 5 8 7 6 2 ) sort print</
=={{header|PHP}}==
{{works with|PHP|4.4.4 CLI}}
<
$nums = array(2,4,3,1,2);
sort($nums);
?></
=={{header|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):
<
-> (1 2 2 3 4)</
=={{header|PL/I}}==
{{works with|IBM PL/I|7.5}}
<
MERGE: PROCEDURE (A,LA,B,LB,C);
Line 2,045 ⟶ 2,071:
CALL MERGE(T,M,AMP1,N-M,A);
RETURN;
END MERGESORT;</
=={{header|Pop11}}==
Pop11 library function sorts lists. So we first convert array to list, then sort and finally convert back:
<
;;; Convert array to list.
;;; destvector leaves its results and on the pop11 stack + an integer saying how many there were
Line 2,060 ⟶ 2,086:
;;; 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:
<
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.)
Line 2,074 ⟶ 2,100:
Alternatively, using the datalist function, even more economically:
<
consvector(destlist(sort(datalist(ar)))) -> ar;</
or in Forth-like pop11 postfix syntax:
<
ar.datalist.sort.destlist.consvector -> ar;</
=={{header|Potion}}==
<
=={{header|PowerBASIC}}==
PowerBASIC has several options available for sorting. At its simplest, an array (of any type) is sorted using <code>ARRAY SORT</code>:
<syntaxhighlight lang
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|Prolog}}==
Line 2,101 ⟶ 2,127:
=={{header|PureBasic}}==
<
For i = 0 To 20
numbers(i) = Random(1000)
Next
SortArray(numbers(), #PB_Sort_Ascending)</
=={{header|Python}}==
{{works with|Python|2.3}}
<
nums.sort()</
'''Note:''' The array <tt>nums</tt> is sorted in place.
Line 2,119 ⟶ 2,145:
You could also use the built-in sorted() function
<
=={{header|Quackery}}==
Line 2,135 ⟶ 2,161:
=={{header|R}}==
<
sorted <- sort(nums)</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
-> (sort '(1 9 2 8 3 7 4 6 5) <)
'(1 2 3 4 5 6 7 8 9)
</syntaxhighlight>
=={{header|Raku}}==
Line 2,148 ⟶ 2,174:
If <code>@a</code> contains only numbers:
<syntaxhighlight lang="raku"
For an in-place sort:
<syntaxhighlight lang="raku"
=={{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]).
<
ok
Line 2,166 ⟶ 2,192:
rascal>sort(a, bool(int a, int b){return a >= b;})
list[int]: [5,4,3,2,1]</
=={{header|Raven}}==
Sort list in place:
<
=={{header|REBOL}}==
<
=={{header|Red}}==
<
== [3 2 6 4 1 9 0 5 7]
>> sort nums
== [0 1 2 3 4 5 6 7 9]</
=={{header|REXX}}==
===sort an array===
This REXX version creates an array with over a score of Euler numbers (integers), then sorts it.
<
numeric digits 30 /*enables handling larger Euler numbers*/
@. = 0; @.1 = 1
Line 2,213 ⟶ 2,239:
do j=1 for #; say _ arg(1) 'array element' right(j, w)"="right(@.j, 20)
end /*j*/
return</
{{out|output|text= when using the default internal input:}}
<pre>
Line 2,267 ⟶ 2,293:
Because it so much more efficient to sort an array, an array is built from the list,
<br>it is then sorted, and then the list is re-constituted.
<
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 " */
Line 2,292 ⟶ 2,318:
end /*i*/
end /*while h>1*/
return</
{{out|output|text= when using the default internal inputs:}}
Line 2,303 ⟶ 2,329:
=={{header|Ring}}==
<
see sort(aArray)</
=={{header|RPL}}==
{{works with|HP|48G}}
{2 4 3 1 2} SORT
{{out}}
<pre>
1: { 1 2 2 3 4 }
</pre>
=={{header|Ruby}}==
<
sorted = nums.sort # returns a new sorted array. 'nums' is unchanged
p sorted #=> [1, 2, 2, 3, 4]
Line 2,313 ⟶ 2,346:
nums.sort! # sort 'nums' "in-place"
p nums #=> [1, 2, 2, 3, 4]</
=={{header|Rust}}==
Uses merge sort in place (undocumented), allocating ~2*n memory where n is a length of an array.
<
let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
a.sort();
println!("{:?}", a);
}</
=={{header|Sather}}==
<
main is
arr: ARRAY{INT} := |4, 6, 7, 2, 1, 0, 100, 21, 34|;
Line 2,335 ⟶ 2,368:
#OUT+" sorted: " + arr + "\n";
end;
end;</
Output:
<syntaxhighlight lang="text">unsorted: {4,6,7,2,1,0,100,21,34}
sorted: {0,1,2,4,6,7,21,34,100}</
=={{header|Scala}}==
{{libheader|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.<
object Sort_an_integer_array extends App {
Line 2,358 ⟶ 2,391:
println(s"Array in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}</
===List===
<
//--> List(-42, 2, 2, 5, 78, 578)</
=={{header|Scheme}}==
{{works with|Guile}}
Same as [[Common Lisp]]
<
{{libheader|Scheme/SRFIs}}
Line 2,372 ⟶ 2,405:
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))
Line 2,379 ⟶ 2,412:
> (vector-sort < #(9 -2 1 2 8 0 1 2))
#(-2 0 1 1 2 2 8 9)
</syntaxhighlight>
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) <)
Line 2,389 ⟶ 2,422:
> (sort #(9 -2 1 2 8 0 1 2) <)
#(-2 0 1 1 2 2 8 9)
</syntaxhighlight>
=={{header|Seed7}}==
<
nums := sort(nums);</
=={{header|Sidef}}==
<
var sorted = nums.sort; # returns a new sorted array.
nums.sort!; # sort 'nums' "in-place"</
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
<
or destructive:
<
=={{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}}==
<
sort(arr);</
=={{header|Standard ML}}==
Line 2,418 ⟶ 2,476:
===Array===
{{works with|SML/NJ}}
<
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}}
<
> val it = () : unit
- load "Int";
Line 2,435 ⟶ 2,493:
> 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] : int list
- val sorted = ListMergeSort.sort op> nums;
val sorted = [1,2,2,3,4] : int list</
{{works with|Moscow ML}}
<
> val it = () : unit
- load "Int";
Line 2,452 ⟶ 2,510:
> 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</
=={{header|Stata}}==
Line 2,458 ⟶ 2,516:
See '''[https://www.stata.com/help.cgi?sort sort]''' in Stata help.
<
. matrix a=(2,9,4,7,5,3,6,1,8)'
. qui svmat a
Line 2,477 ⟶ 2,535:
8. | 8 |
9. | 9 |
+----+</
=== Sort a macro list ===
See '''[https://www.stata.com/help.cgi?macrolists macrolists]''' in Stata help for other functions on lists stored in macros.
<
. di "`: list sort a'"
1 2 3 4 5 6 7 8 9</
=== Mata ===
See Mata's '''[http://www.stata.com/help.cgi?mf_sort sort]''' function.
<
: a=2\9\4\7\5\3\6\1\8
Line 2,505 ⟶ 2,563:
9 | 9 |
+-----+
end</
=={{header|Swift}}==
===Sort in place===
{{works with|Swift|2.x+}}
<
nums.sortInPlace()
print(nums)</
or
<
nums.sortInPlace(<)
print(nums)</
{{works with|Swift|1.x}}
<
nums.sort(<)
println(nums)</
or
<
sort(&nums)
println(nums)</
or
<
sort(&nums, <)
println(nums)</
===Return new array===
Line 2,535 ⟶ 2,593:
{{works with|Swift|2.x+}}
<
print(nums)</
or
<
print(nums)</
{{works with|Swift|1.x}}
<
println(nums)</
or
<
println(nums)</
=={{header|Tcl}}==
<
=={{header|TI-83 BASIC}}==
Line 2,560 ⟶ 2,618:
This can be done by using the bubble sort library:
<
arrayname number_elements bsort</
See the Toka entry on [[Bubble Sort]] for a full example.
Line 2,568 ⟶ 2,626:
Each shell parameter separates the integers using the default IFS whitespace (space, tab, newline).
<
sorted=`printf "%s\n" $nums | sort -n`
echo $sorted # prints 1 2 3 4 5</
Alternate solution: <tt>sorted=`for i in $nums; do echo $i; done | sort -n`</tt>
Line 2,578 ⟶ 2,636:
{{works with|pdksh|5.2.14}}
<
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 <tt>nums=(2 4 3 1 2)</tt> syntax.
=={{header|Ursa}}==
<
append 2 4 3 1 2 nums
sort nums</
=={{header|Ursala}}==
using the built in sort operator, -<, with the nleq library function
for comparing natural numbers
<
#cast %nL
example = nleq-< <39,47,40,53,14,23,88,52,78,62,41,92,88,66,5,40></
output:
<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)
}</
{{out}}
Line 2,613 ⟶ 2,671:
=={{header|WDTE}}==
<
a.sort [39; 47; 40; 53; 14; 23; 88; 52; 78; 62; 41; 92; 88; 66; 5; 40] < -- io.writeln io.stdout;</
=={{header|Wortel}}==
<
=={{header|Wren}}==
{{libheader|Wren-sort}}
<
var a = [7, 10, 2, 4, 6, 1, 8, 3, 9, 5]
Sort.quick(a)
System.print(a)</
{{out}}
Line 2,633 ⟶ 2,691:
=={{header|XPL0}}==
<
proc SSort(A, N); \Shell sort array in ascending order
Line 2,659 ⟶ 2,717:
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
]</
Output:
Line 2,667 ⟶ 2,725:
=={{header|Yabasic}}==
<
// Shell sort based on insertion sort
Line 2,722 ⟶ 2,780:
next n
end if</
=={{header|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));
</syntaxhighlight>
=={{header|zkl}}==
In place sorting read/write list:
<
Sort a read only list:
<
b.println(); //--> L(2,4,5,6)
a.println(); //--> L(4,5,2,6)</
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: sort_integer_array
input: [2,4,3,1]
output: [1,2,3,4]
</syntaxhighlight>
=={{header|Zoea Visual}}==
|