Sorting an Array of Integers
From Rosetta Code
Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.
Contents |
[edit] 4D
[edit] 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
[edit] 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
[edit] 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;
[edit] 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
[edit] C
Works with: gcc version 4.0.1
#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);
}
[edit] C++
Works with: g++ version 4.0.1
[edit] Simple Array
#include <algorithm>
int main()
{
int nums[] = {2,4,3,1,2};
std::sort(nums, nums+5);
}
[edit] 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());
}
[edit] 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();
}
[edit] 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}
[edit] 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)
[edit] D
auto nums = [2,4,3,1,2]; auto snums = nums.dup.sort; // Sort nums.sort; // Sort in-place
[edit] E
[2,4,3,1,2].sort()
[edit] Erlang
List = [2, 4, 3, 1, 2]. SortedList = lists:sort(List).
[edit] Forth
Works with: Win32Forth version 4.2
create test-data 2 , 4 , 3 , 1 , 2 , test-data 5 cell-sort
[edit] 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.
[edit] Haskell
Works with: GHCi version 6.6
nums = [2,4,3,1,2] :: [Int] sorted = List.sort nums
[edit] IDL
result = array[sort(array)]
[edit] J
/:~
The verb /:~ sorts anything. 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.
This code also applies to any data type.
[edit] Java
[edit] Array
import java.util.Arrays;
public class example {
public static void main(String[] args)
{
int[] nums = {2,4,3,1,2};
Arrays.sort(nums);
}
}
[edit] 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);
}
}
[edit] 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 numberSorter(a, b) {
return a - b;
}
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
numbers.sort(numberSorter);
alert( numbers );
[edit] Mathematica
numbers = Sort[{2,4,3,1,2}]
[edit] MAXScript
arr = #(5, 4, 3, 2, 1) arr = sort arr
[edit] Nial
sort >= 9 6 8 7 1 10 = 10 9 8 7 6 1
[edit] Objective-C
Works with: GCC version 4.0.1 (apple)
- (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:)];
}
[edit] OCaml
[edit] Array
let nums = [|2; 4; 3; 1; 2|] Array.sort compare nums
[edit] List
let nums = [2; 4; 3; 1; 2] let sorted = List.sort compare nums
[edit] Perl
Works with: Perl version 5.8.6
@nums = (2,4,3,1,2);
@sorted = sort {$a <=> $b} @nums;
[edit] PHP
Works with: PHP version 4.4.4 CLI
<?php $nums = array(2,4,3,1,2); sort($nums); ?>
[edit] 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;
[edit] 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])
[edit] R
nums <- (2,4,3,1,2) sorted <- sort(nums)
[edit] Raven
Sort list in place:
[ 2 4 3 1 2 ] sort
[edit] Ruby
Works with: Ruby version 1.8.4
nums = [2,4,3,1,2] sorted = nums.sort
[edit] Seed7
var array integer: nums is [] (2, 4, 3, 1, 2);
nums := sort(nums);
[edit] Smalltalk
#(7 5 2 9 0 -1) asSortedCollection
[edit] Tcl
set result [lsort -integer $unsorted_list]
[edit] 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.
[edit] UNIX Shell
[edit] Bourne Again SHell
nums=(2 4 3 1 2)
sorted=($(for i in ${nums[*]}; do echo $i; done | sort -n))
Categories: Programming Tasks | Sorting | 4D | Ada | APL | C | C++ | Clean | Common Lisp | D | E | Erlang | Forth | Fortran | Haskell | IDL | J | Java | JavaScript | Mathematica | MAXScript | Nial | Objective-C | OCaml | Perl | PHP | Pop11 | Python | R | Raven | Ruby | Seed7 | Smalltalk | Tcl | Toka | UNIX Shell

