Sort an integer array: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Typo fix)
m (Syntax highlighting)
Line 4: Line 4:
===English===
===English===


ARRAY INTEGER($nums;0)
<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)
APPEND TO ARRAY($nums;3)
APPEND TO ARRAY($nums;3)
APPEND TO ARRAY($nums;1)
APPEND TO ARRAY($nums;1)
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
SORT ARRAY($nums;<) ` sort in descending order</lang>


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


TABLEAU ENTIER($nombres;0)
<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)
AJOUTER A TABLEAU($nombres;3)
AJOUTER A TABLEAU($nombres;3)
AJOUTER A TABLEAU($nombres;1)
AJOUTER A TABLEAU($nombres;1)
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
TRIER TABLEAU($nombres;<) ` pour effectuer un tri par ordre décroissant</lang>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2006}}
{{works with|GNAT|GPL 2006}}
<lang ada>
<lang ada>with Gnat.Heap_Sort_G;
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
procedure Integer_Sort is
package Heap_Sort is new Gnat.Heap_Sort_G(Move_Int, Lt_Int);
-- 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;


begin
Heap_Sort.Sort(8);
end Integer_Sort;


requires an Ada05 compiler, e.g GNAT GPL 2007
requires an Ada05 compiler, e.g GNAT GPL 2007
with Ada.Containers.Generic_Array_Sort;
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);
procedure Integer_Sort is
begin
Sort(Values);
--
type Int_Array is array(Natural range <>) of Integer;
end Integer_Sort;
Values : Int_Array := (0,1,8,2,7,3,6,4,5);
</lang>
-- 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;</lang>
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|python}}
{{trans|python}}
Line 114: Line 111:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>
<lang AutoHotkey>numbers = 5 4 1 2 3
numbers = 5 4 1 2 3
sort, numbers, N D%A_Space%
sort, numbers, N D%A_Space%
Msgbox % numbers
Msgbox % numbers</lang>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 139: Line 134:


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

int main()
int main()
{
{
int nums[] = {2,4,3,1,2};
int nums[] = {2,4,3,1,2};
std::sort(nums, nums+5);
std::sort(nums, nums+5);
}</lang>
}


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

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


===<tt>std::list</tt>===
===<tt>std::list</tt>===
#include <list>
<lang cpp>#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();
}


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();
}</lang>
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


Line 190: Line 184:
=={{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.
import StdEnv
<lang clean>import StdEnv

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

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


=={{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) #'<)

#(-2 0 1 1 2 2 8 9)</lang>

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


=={{header|D}}==
=={{header|D}}==
auto nums = [2,4,3,1,2];
<lang d>auto nums = [2,4,3,1,2];
auto snums = nums.dup.sort; // Sort
auto snums = nums.dup.sort; // Sort
nums.sort; // Sort in-place
nums.sort; // Sort in-place</lang>


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


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


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|Win32Forth|4.2}}
{{works with|Win32Forth|4.2}}
create test-data 2 , 4 , 3 , 1 , 2 ,
<lang forth>create test-data 2 , 4 , 3 , 1 , 2 ,
test-data 5 cell-sort
test-data 5 cell-sort</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Silverfrost FTN95}}
{{works with|Silverfrost FTN95}}
CALL ISORT@(b, a, n)
<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.
! b = array of indices of a. b(1) 'points' to the minimum value etc.</lang>



=={{header|Groovy}}==
=={{header|Groovy}}==
Line 239: Line 230:
{{works with|GHC|GHCi|6.6}}
{{works with|GHC|GHCi|6.6}}
nums = [2,4,3,1,2] :: [Int]
<lang haskell>nums = [2,4,3,1,2] :: [Int]
sorted = List.sort nums
sorted = List.sort nums</lang>


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


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


] a=: 10 ?@$ 100 NB. random vector
<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
15 36 39 43 51 63 69 89 92 92</lang>
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.
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.
<br>This code also applies to any data type.
<br>This code also applies to any data type.
Line 258: Line 249:
=={{header|Java}}==
=={{header|Java}}==
===Array===
===Array===
import java.util.Arrays;
<lang java>import java.util.Arrays;

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


===List===
===List===
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
import java.util.Arrays;
<lang java5>import java.util.Arrays;
import java.util.Collections;
import java.util.Collections;
import java.util.List;
import java.util.List;

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


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 287: Line 278:
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.


function numberSorter(a, b) {
<lang javascript>function numberSorter(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(numberSorter);
numbers.sort(numberSorter);
alert( numbers );
alert( numbers );</lang>

=={{header|Mathematica}}==
=={{header|Mathematica}}==
numbers = Sort[{2,4,3,1,2}]
<lang mathemetica>numbers = Sort[{2,4,3,1,2}]</lang>


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


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


=={{header|Objective-C}}==
=={{header|Objective-C}}==
{{works with|GCC|4.0.1 (apple)}}
{{works with|GCC|4.0.1 (apple)}}
- (void)example
<lang objc>- (void)example
{
{
NSArray *nums, *sorted;
NSArray *nums, *sorted;
nums = [NSArray arrayWithObjects:
nums = [NSArray arrayWithObjects:
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:4],
[NSNumber numberWithInt:4],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:2],
nil];
nil];
sorted = [nums sortedArrayUsingSelector:@selector(compare:)];
sorted = [nums sortedArrayUsingSelector:@selector(compare:)];
}</lang>
}


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


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


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


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


=={{header|PL/I}}==
=={{header|PL/I}}==
{{works with|IBM PL/I|7.5}}
{{works with|IBM PL/I|7.5}}
<lang PL/I>
<lang PL/I>
DCL (T(10)) FIXED BIN(31); /* scratch space of length N/2 */
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);
DECLARE (A(*),B(*),C(*)) FIXED BIN(31);
DECLARE (A(*),B(*),C(*)) FIXED BIN(31);
DECLARE (LA,LB) FIXED BIN(31) NONASGN;
DECLARE (LA,LB) FIXED BIN(31) NONASGN;
DECLARE (I,J,K) FIXED BIN(31);
DECLARE (I,J,K) FIXED BIN(31);
I=1; J=1; K=1;
I=1; J=1; K=1;
DO WHILE ((I <= LA) & (J <= LB));
DO WHILE ((I <= LA) & (J <= LB));
IF(A(I) <= B(J)) THEN
IF(A(I) <= B(J)) THEN
DO; C(K)=A(I); K=K+1; I=I+1; END;
DO; C(K)=A(I); K=K+1; I=I+1; END;
ELSE
ELSE
DO; C(K)=B(J); K=K+1; J=J+1; END;
DO; C(K)=B(J); K=K+1; J=J+1; END;
END;
END;
DO WHILE (I <= LA);
DO WHILE (I <= LA);
C(K)=A(I); I=I+1; K=K+1;
C(K)=A(I); I=I+1; K=K+1;
END;
END;
RETURN;
RETURN;
END MERGE;
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;


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;
IF (N=1) THEN RETURN;
M = trunc((N+1)/2);
M = trunc((N+1)/2);
IF (M>1) THEN CALL MERGESORT(A,M);
IF (M>1) THEN CALL MERGESORT(A,M);
P=ADDR(A(M+1));
P=ADDR(A(M+1));
IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M);
IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M);
IF A(M) <= AMP1(1) THEN RETURN;
IF A(M) <= AMP1(1) THEN RETURN;
DO I=1 to M; T(I)=A(I); END;
DO I=1 to M; T(I)=A(I); END;
CALL MERGE(T,M,AMP1,N-M,A);
CALL MERGE(T,M,AMP1,N-M,A);
RETURN;
RETURN;
END MERGESORT;
END MERGESORT;
</lang>
</lang>


Line 393: Line 382:
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:


lvars ar = {2 4 3 1 2};
<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
destvector(ar);
destvector(ar);
;;; conslist uses the items left on the stack plus the integer, to make a list of those items.
;;; conslist uses the items left on the stack plus the integer, to make a list of those items.
lvars ls = conslist();
lvars ls = conslist();
;;; Sort it
;;; Sort it
sort(ls) -> ls;
sort(ls) -> ls;
;;; Convert list to array
;;; Convert list to array
destlist(ls);
destlist(ls);
consvector() -> ar;
consvector() -> ar;</lang>


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:


lvars ar = {2 4 3 1 2};
<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}
** {1 2 2 3 4}</lang>


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


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


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


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


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


'''Note:''' The array <tt>nums</tt> is sorted in place.
'''Note:''' The array <tt>nums</tt> is sorted in place.
Line 437: Line 426:
You could also use the built-in sorted() function
You could also use the built-in sorted() function


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



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


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


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


=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.8.4}}
{{works with|Ruby|1.8.4}}
nums = [2,4,3,1,2]
<lang ruby>nums = [2,4,3,1,2]
sorted = nums.sort
sorted = nums.sort</lang>


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


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


=={{header|Slate}}==
=={{header|Slate}}==
Line 468: Line 456:
===Array===
===Array===
{{works with|SML/NJ}}
{{works with|SML/NJ}}
val nums = Array.fromList [2, 4, 3, 1, 2];
<lang sml>val nums = Array.fromList [2, 4, 3, 1, 2];
ArrayQSort.sort Int.compare nums;
ArrayQSort.sort Int.compare nums;</lang>


===List===
===List===
{{works with|SML/NJ}}
{{works with|SML/NJ}}
val nums = [2, 4, 3, 1, 2];
<lang sml>val nums = [2, 4, 3, 1, 2];
val sorted = ListMergeSort.sort (op >) nums;
val sorted = ListMergeSort.sort (op >) nums;</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 482: Line 470:
This can be done by using the bubble sort library:
This can be done by using the bubble sort library:


needs bsort
<lang toka>needs bsort
arrayname number_elements bsort
arrayname number_elements bsort</lang>


See the Toka entry on [[Bubble Sort]] for a full example.
See the Toka entry on [[Bubble Sort]] for a full example.
Line 489: Line 477:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
===[[Bourne Again SHell]]===
===[[Bourne Again SHell]]===
nums=(2 4 3 1 2)
<lang bash>nums=(2 4 3 1 2)
sorted=($(for i in ${nums[*]}; do echo $i; done | sort -n))
sorted=($(for i in ${nums[*]}; do echo $i; done | sort -n))</lang>

Revision as of 18:56, 23 June 2009

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

Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.

4D

English

<lang 4d>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</lang>

Français

<lang 4d>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</lang>

Ada

Works with: GNAT version GPL 2006

<lang ada>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;</lang>

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

<lang algol>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))</lang> Output:

         +1         +2         +2         +3         +4

APL

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

AutoHotkey

<lang AutoHotkey>numbers = 5 4 1 2 3 sort, numbers, N D%A_Space% Msgbox % numbers</lang>

C

Works with: gcc version 4.0.1

<lang c> #include <stdlib.h>

int intcmp(const void *a, const void *b)
{
    return *(int *)a - *(int *)b;
}

int main()
{
    int nums[5] = {2,4,3,1,2};
    qsort(nums, 5, sizeof(int), intcmp);
}</lang>

C++

Works with: g++ version 4.0.1

Simple Array

<lang cpp>#include <algorithm>

int main() {

   int nums[] = {2,4,3,1,2};
   std::sort(nums, nums+5);

}</lang>

std::vector

<lang cpp>#include <algorithm>

  1. 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());

}</lang>

std::list

<lang cpp>#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();

}</lang>

C#

<lang csharp>using System; using System.Collections.Generic;

public class Program {

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

}</lang>

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. <lang clean>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}</lang>

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: <lang lisp>CL-USER> (sort #(9 -2 1 2 8 0 1 2) #'<)

  1. (-2 0 1 1 2 2 8 9)</lang>

D

<lang d>auto nums = [2,4,3,1,2]; auto snums = nums.dup.sort; // Sort nums.sort; // Sort in-place</lang>

E

<lang e>[2,4,3,1,2].sort()</lang>

Erlang

<lang erlang>List = [2, 4, 3, 1, 2]. SortedList = lists:sort(List).</lang>

Forth

Works with: Win32Forth version 4.2

<lang forth>create test-data 2 , 4 , 3 , 1 , 2 , test-data 5 cell-sort</lang>

Fortran

Works with: Silverfrost FTN95

<lang fortran>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.</lang>

Groovy

<lang groovy>println ([2,4,0,3,1,2,-12].sort())</lang>

Output:

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

Haskell

Works with: GHCi version 6.6

<lang haskell>nums = [2,4,3,1,2] :: [Int] sorted = List.sort nums</lang>

IDL

<lang idl>result = array[sort(array)]</lang>

J

<lang j>/:~</lang> The verb /:~ sorts anything. For example:

<lang j> ] 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</lang> 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.
This code also applies to any data type.

Java

Array

<lang java>import java.util.Arrays;

public class example {

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

}</lang>

List

Works with: Java version 1.5+

<lang java5>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);
   }

}</lang>

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.

<lang javascript>function numberSorter(a, b) {

 return a - b;

} var numbers = [20, 7, 65, 10, 3, 0, 8, -60]; numbers.sort(numberSorter); alert( numbers );</lang>

Mathematica

<lang mathemetica>numbers = Sort[{2,4,3,1,2}]</lang>

MAXScript

<lang maxscript>arr = #(5, 4, 3, 2, 1) arr = sort arr</lang>

Nial

<lang nial>sort >= 9 6 8 7 1 10 = 10 9 8 7 6 1</lang>

Objective-C

Works with: GCC version 4.0.1 (apple)

<lang objc>- (void)example {

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

}</lang>

OCaml

Array

<lang ocaml>let nums = [|2; 4; 3; 1; 2|] Array.sort compare nums</lang>

List

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

Octave

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

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

Perl

Works with: Perl version 5.8.6

<lang perl>@nums = (2,4,3,1,2); @sorted = sort {$a <=> $b} @nums;</lang>

PHP

Works with: PHP version 4.4.4 CLI

<lang php><?php $nums = array(2,4,3,1,2); sort($nums); ?></lang>

PL/I

Works with: IBM PL/I version 7.5

<lang PL/I> 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; </lang>

Pop11

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};

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;</lang>

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}; consvector(destlist(sort(conslist(destvector(ar))))) -> ar;

print the sorted vector

ar =>

    • {1 2 2 3 4}</lang>

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

Alternatively, using the datalist function, even more economically:

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


or in Forth-like pop11 postfix syntax:

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

Python

Works with: Python version 2.3

<lang python>nums = [2,4,3,1,2] nums.sort()</lang>

Note: The array nums is sorted in place.

Interpreter: Python 2.4 (and above)

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

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

R

<lang r>nums <- (2,4,3,1,2) sorted <- sort(nums)</lang>

Raven

Sort list in place:

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

Ruby

Works with: Ruby version 1.8.4

<lang ruby>nums = [2,4,3,1,2] sorted = nums.sort</lang>

Seed7

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

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

Slate

<lang slate> #(7 5 2 9 0 -1) sort</lang>

Smalltalk

<lang smalltalk> #(7 5 2 9 0 -1) asSortedCollection</lang>

Standard ML

Array

Works with: SML/NJ

<lang sml>val nums = Array.fromList [2, 4, 3, 1, 2]; ArrayQSort.sort Int.compare nums;</lang>

List

Works with: SML/NJ

<lang sml>val nums = [2, 4, 3, 1, 2]; val sorted = ListMergeSort.sort (op >) nums;</lang>

Tcl

<lang tcl>set result [lsort -integer $unsorted_list]</lang>

Toka

This can be done by using the bubble sort library:

<lang toka>needs bsort arrayname number_elements bsort</lang>

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

UNIX Shell

Bourne Again SHell

<lang bash>nums=(2 4 3 1 2) sorted=($(for i in ${nums[*]}; do echo $i; done | sort -n))</lang>