task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#CLU
CLU
% Bubble-sort an array in place. bubble_sort = proc [T: type] (a: array[T]) where T has lt: proctype (T,T) returns (bool)   bound_lo: int := array[T]$low(a) bound_hi: int := array[T]$high(a)   for hi: int in int$from_to_by(bound_hi, bound_lo, -1) do for i: int in int$from_to(bound_lo, hi-1) do if a[hi] < a[i] then temp: T := a[i] a[i] := a[hi] a[hi] := temp end end end end bubble_sort   % Print an array print_arr = proc [T: type] (a: array[T], w: int, s: stream) where T has unparse: proctype (T) returns (string) for el: T in array[T]$elements(a) do stream$putright(s, T$unparse(el), w) end stream$putc(s, '\n') end print_arr   start_up = proc () ai = array[int] po: stream := stream$primary_output() test: ai := ai$[7, -5, 0, 2, 99, 16, 4, 20, 47, 19]   stream$puts(po, "Before: ") print_arr[int](test, 3, po) bubble_sort[int](test) stream$puts(po, "After: ") print_arr[int](test, 3, po) end start_up
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#IS-BASIC
IS-BASIC
  100 PROGRAM "GnomeSrt.bas" 110 RANDOMIZE 120 NUMERIC ARRAY(-5 TO 12) 130 CALL INIT(ARRAY) 140 CALL WRITE(ARRAY) 150 CALL GNOMESORT(ARRAY) 160 CALL WRITE(ARRAY) 170 DEF INIT(REF A) 180 FOR I=LBOUND(A) TO UBOUND(A) 190 LET A(I)=RND(98)+1 200 NEXT 210 END DEF 220 DEF WRITE(REF A) 230 FOR I=LBOUND(A) TO UBOUND(A) 240 PRINT A(I); 250 NEXT 260 PRINT 270 END DEF 280 DEF GNOMESORT(REF A) 290 LET I=LBOUND(A)+1:LET J=I+1 300 DO WHILE I<=UBOUND(A) 310 IF A(I-1)<=A(I) THEN 320 LET I=J:LET J=J+1 330 ELSE 340 LET T=A(I-1):LET A(I-1)=A(I):LET A(I)=T 350 LET I=I-1 360 IF I=LBOUND(A) THEN LET I=J:LET J=J+1 370 END IF 380 LOOP 390 END DEF
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION beadSort RETURNS CHAR ( i_c AS CHAR ):   DEF VAR cresult AS CHAR. DEF VAR ii AS INT. DEF VAR inumbers AS INT. DEF VAR irod AS INT. DEF VAR irods AS INT. DEF VAR crod AS CHAR. DEF VAR cbeads AS CHAR EXTENT.   inumbers = NUM-ENTRIES( i_c ).   /* determine number of rods needed */ DO ii = 1 TO inumbers: irods = MAXIMUM( irods, INTEGER( ENTRY( ii, i_c ) ) ). END.   /* put beads on rods */ EXTENT( cbeads ) = inumbers. DO ii = 1 TO inumbers: cbeads[ ii ] = FILL( "X", INTEGER( ENTRY( ii, i_c ) ) ). END.   /* drop beads on each rod */ DO irod = 1 TO irods: crod = "". DO ii = 1 TO inumbers: crod = crod + SUBSTRING( cbeads[ ii ], irod, 1 ). END. crod = REPLACE( crod, " ", "" ). DO ii = 1 TO inumbers. SUBSTRING( cbeads[ ii ], irod, 1 ) = STRING( ii <= LENGTH( crod ), "X/ " ). END. END.   /* get beads from rods */ DO ii = 1 TO inumbers: cresult = cresult + "," + STRING( LENGTH( REPLACE( cbeads[ ii ], " ", "" ) ) ). END.   RETURN SUBSTRING( cresult, 2 ).   END FUNCTION. /* beadSort */   MESSAGE "5,2,4,1,3,3,9 -> " beadSort( "5,2,4,1,3,3,9" ) SKIP "5,3,1,7,4,1,1 -> " beadSort( "5,3,1,7,4,1,1" ) SKIP(1) beadSort( "88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1" ) VIEW-AS ALERT-BOX.
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#PARI.2FGP
PARI/GP
beadsort(v)={ my(sz=vecmax(v),M=matrix(#v,sz,i,j,v[i]>=j)); \\ Set up beads for(i=1,sz,M[,i]=countingSort(M[,i],0,1)~); \\ Let them fall vector(#v,i,value(M[i,])) \\ Convert back to numbers };   countingSort(v,mn,mx)={ my(u=vector(#v),i=0); for(n=mn,mx, for(j=1,#v,if(v[j]==n,u[i++]=n)) ); u };   value(v)={ if(#v==0 || !v[1], return(0)); if(v[#v], return(#v)); my(left=1, right=#v, mid); while (right - left > 1, mid=(right+left)\2; if(v[mid], left=mid, right=mid) ); left };
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Haskell
Haskell
cocktailSort :: Ord a => [a] -> [a] cocktailSort l | not swapped1 = l | not swapped2 = reverse $ l1 | otherwise = cocktailSort l2 where (swapped1, l1) = swappingPass (>) (False, []) l (swapped2, l2) = swappingPass (<) (False, []) l1   swappingPass :: Ord a => (a -> a -> Bool) -> (Bool, [a]) -> [a] -> (Bool, [a]) swappingPass op (swapped, l) (x1 : x2 : xs) | op x1 x2 = swappingPass op (True, x2 : l) (x1 : xs) | otherwise = swappingPass op (swapped, x1 : l) (x2 : xs) swappingPass _ (swapped, l) [x] = (swapped, x : l) swappingPass _ pair [] = pair
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Pascal
Pascal
program CountingSort;   procedure counting_sort(var arr : Array of Integer; n, min, max : Integer); var count : Array of Integer; i, j, z : Integer; begin SetLength(count, max-min); for i := 0 to (max-min) do count[i] := 0; for i := 0 to (n-1) do count[ arr[i] - min ] := count[ arr[i] - min ] + 1; z := 0; for i := min to max do for j := 0 to (count[i - min] - 1) do begin arr[z] := i; z := z + 1 end end;   var ages : Array[0..99] of Integer; i : Integer;   begin { testing } for i := 0 to 99 do ages[i] := 139 - i; counting_sort(ages, 100, 0, 140); for i := 0 to 99 do writeln(ages[i]); end.
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#ALGOL_68
ALGOL 68
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))
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Action.21
Action!
DEFINE PTR="CARD"   PROC PrintArray(PTR ARRAY a INT size) INT i   FOR i=0 TO size-1 DO PrintE(a(i)) OD RETURN   INT FUNC Decode(CHAR ARRAY s INT ARRAY a) INT count BYTE i,begin,end CHAR ARRAY tmp(10)   count=0 i=1 WHILE i<=s(0) DO begin=i WHILE i<=s(0) AND s(i)#'. DO i==+1 OD end=i-1 IF i<s(0) THEN i==+1 FI SCopyS(tmp,s,begin,end) a(count)=ValI(tmp) count==+1 OD RETURN (count)   INT FUNC Compare(CHAR ARRAY s1,s2) INT ARRAY a1(20),a2(20) INT c1,c2,res BYTE i   c1=Decode(s1,a1) c2=Decode(s2,a2)   i=0 DO IF i=c1 AND i=c2 THEN RETURN (0) ELSEIF i=c1 THEN RETURN (-1) ELSEIF i=c2 THEN RETURN (1) FI   IF a1(i)<a2(i) THEN RETURN (-1) ELSEIF a1(i)>a2(i) THEN RETURN (1) FI i==+1 OD RETURN (0)   PROC Sort(PTR ARRAY a INT size) INT i,j,minpos CHAR ARRAY tmp   FOR i=0 TO size-2 DO minpos=i FOR j=i+1 TO size-1 DO IF Compare(a(minpos),a(j))>0 THEN minpos=j FI OD   IF minpos#i THEN tmp=a(i) a(i)=a(minpos) a(minpos)=tmp FI OD RETURN   PROC Main() DEFINE SIZE="6" PTR ARRAY a(SIZE)   a(0)="1.3.6.1.4.1.11.2.17.19.3.4.0.10" a(1)="1.3.6.1.4.1.11.2.17.5.2.0.79" a(2)="1.3.6.1.4.1.11.2.17.19.3.4.0.4" a(3)="1.3.6.1.4.1.11150.3.4.0.1" a(4)="1.3.6.1.4.1.11.2.17.19.3.4.0.1" a(5)="1.3.6.1.4.1.11150.3.4.0"   PrintE("Array before sort:") PrintArray(a,SIZE) PutE()   Sort(a,SIZE) PrintE("Array after sort:") PrintArray(a,SIZE) RETURN
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Ada
Ada
with Ada.Containers.Generic_Array_Sort; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Unchecked_Deallocation;   procedure Sort_List_Identifiers is type Natural_Array is array (Positive range <>) of Natural; type Unbounded_String_Array is array(Positive range <>) of Unbounded_String;   function To_Natural_Array(input : in String) return Natural_Array is target : Natural_Array(1 .. Ada.Strings.Fixed.Count(input, ".") + 1); from : Natural := input'First; to : Natural := Ada.Strings.Fixed.Index(input, "."); index : Positive := target'First; begin while to /= 0 loop target(index) := Natural'Value(input(from .. to - 1)); from := to + 1; index := index + 1; to := Ada.Strings.Fixed.Index(input, ".", from); end loop; target(index) := Natural'Value(input(from .. input'Last)); return target; end To_Natural_Array;   function Lesser(Left, Right : in Unbounded_String) return Boolean is begin return To_Natural_Array(To_String(Left)) < To_Natural_Array(To_String(Right)); end Lesser;   procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Positive, Element_Type => Unbounded_String, Array_Type => Unbounded_String_Array, "<" => Lesser);   table : Unbounded_String_Array := (To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.10"), To_Unbounded_String("1.3.6.1.4.1.11.2.17.5.2.0.79"), To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.4"), To_Unbounded_String("1.3.6.1.4.1.11150.3.4.0.1"), To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.1"), To_Unbounded_String("1.3.6.1.4.1.11150.3.4.0")); begin Sort(table); for element of table loop Ada.Text_IO.Put_Line(To_String(element)); end loop; end Sort_List_Identifiers;
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#C
C
#include <stdio.h>   /* yes, bubble sort */ void bubble_sort(int *idx, int n_idx, int *buf) { int i, j, tmp; #define for_ij for (i = 0; i < n_idx; i++) for (j = i + 1; j < n_idx; j++) #define sort(a, b) if (a < b) { tmp = a; a = b; b = tmp;} for_ij { sort(idx[j], idx[i]); } for_ij { sort(buf[idx[j]], buf[idx[i]]);} #undef for_ij #undef sort }   int main() { int values[] = {7, 6, 5, 4, 3, 2, 1, 0}; int idx[] = {6, 1, 7}; int i;   printf("before sort:\n"); for (i = 0; i < 8; i++) printf("%d ", values[i]);   printf("\n\nafter sort:\n"); bubble_sort(idx, 3, values);   for (i = 0; i < 8; i++) printf("%d ", values[i]); printf("\n");   return 0; }
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#J
J
import java.util.Arrays; import java.util.Comparator;   public class RJSortStability {   public static void main(String[] args) { String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", };   String[] cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String city : cn) { System.out.println(city); }   // sort by city Arrays.sort(cn, new Comparator<String>() { public int compare(String lft, String rgt) { return lft.substring(4).compareTo(rgt.substring(4)); } });   System.out.println("\nAfter sort on city:"); for (String city : cn) { System.out.println(city); }   cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String city : cn) { System.out.println(city); }   // sort by country Arrays.sort(cn, new Comparator<String>() { public int compare(String lft, String rgt) { return lft.substring(0, 2).compareTo(rgt.substring(0, 2)); } });   System.out.println("\nAfter sort on country:"); for (String city : cn) { System.out.println(city); }   System.out.println(); } }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#PicoLisp
PicoLisp
(println (by format sort (range 1 13) ) )
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Prolog
Prolog
lexicographical_sort(Numbers, Sorted_numbers):- number_strings(Numbers, Strings), sort(Strings, Sorted_strings), number_strings(Sorted_numbers, Sorted_strings).   number_strings([], []):-!. number_strings([Number|Numbers], [String|Strings]):- number_string(Number, String), number_strings(Numbers, Strings).   number_list(From, To, []):- From > To, !. number_list(From, To, [From|Rest]):- Next is From + 1, number_list(Next, To, Rest).   lex_sorted_number_list(Number, List):- (Number < 1 -> number_list(Number, 1, Numbers) ; number_list(1, Number, Numbers) ), lexicographical_sort(Numbers, List).   test(Number):- lex_sorted_number_list(Number, List), writef('%w: %w\n', [Number, List]).   main:- test(0), test(5), test(13), test(21), test(-22).
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#IS-BASIC
IS-BASIC
100 LET X=77444:LET Y=-12:LET Z=0 110 PRINT X;Y;Z 120 CALL SHORT(X,Y,Z) 130 PRINT X;Y;Z 140 DEF SHORT(REF A,REF B,REF C) 150 IF A>B THEN LET T=A:LET A=B:LET B=T 160 IF B>C THEN LET T=B:LET B=C:LET C=T 170 IF A>B THEN LET T=A:LET A=B:LET B=T 180 END DEF
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#J
J
x =: 'lions, tigers, and' y =: 'bears, oh my!' z =: '(from the "Wizard of OZ")' 'x y z'=: /:~".'x;y;<z' x (from the "Wizard of OZ") y bears, oh my! z lions, tigers, and   x =: 77444 y =: -12 z =: 0 'x y z'=: /:~".'x;y;<z' x _12 y 0 z 77444
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Factor
Factor
: my-compare ( s1 s2 -- <=> ) 2dup [ length ] compare invert-comparison dup +eq+ = [ drop [ >lower ] compare ] [ 2nip ] if ;   { "this" "is" "a" "set" "of" "strings" "to" "sort" } [ my-compare ] sort
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#PureBasic
PureBasic
;sorts an array of integers Procedure combSort11(Array a(1)) Protected i, gap, swaps = 1 Protected nElements = ArraySize(a())   gap = nElements While (gap > 1) Or (swapped = 1) gap * 10 / 13 If gap = 9 Or gap = 10: gap = 11: EndIf If gap < 1: gap = 1: EndIf   i = 0 swaps = 0 While (i + gap) <= nElements If a(i) > a(i + gap) Swap a(i), a(i + gap) swaps = 1 EndIf i + 1 Wend Wend EndProcedure
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#PARI.2FGP
PARI/GP
bogosort(v)={ while(1, my(u=vecextract(v,numtoperm(#v,random((#v)!)))); for(i=2,#v,if(u[i]<u[i-1], next(2))); return(u) ); };
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#CMake
CMake
# bubble_sort(var [value1 value2...]) sorts a list of integers. function(bubble_sort var) math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last]. set(again YES) while(again) set(again NO) math(EXPR last "${last} - 1") # Decrement last index. foreach(index RANGE 1 ${last}) # Loop for each index. math(EXPR index_plus_1 "${index} + 1") set(a "${ARGV${index}}") # a = ARGV[index] set(b "${ARGV${index_plus_1}}") # b = ARGV[index + 1] if(a GREATER "${b}") # If a > b... set(ARGV${index} "${b}") # ...then swap a, b set(ARGV${index_plus_1} "${a}") # inside ARGV. set(again YES) endif() endforeach(index) endwhile()   set(answer) math(EXPR last "${ARGC} - 1") foreach(index RANGE 1 "${last}") list(APPEND answer "${ARGV${index}}") endforeach(index) set("${var}" "${answer}" PARENT_SCOPE) endfunction(bubble_sort)
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#J
J
position=: 0 {.@I.@, [ swap=: ] A.~ *@position * #@[ !@- <:@position gnome=: swap~ 2 >/\ ] gnomes=: gnome^:_
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Pascal
Pascal
  program BDS; const MAX = 1000; type type_matrix = record lin,col:integer; matrix: array [1..MAX,1..MAX] of boolean; end;   type_vector = record size:integer; vector: array[1..MAX] of integer; end;   procedure BeadSort(var v:type_vector); var i,j,k,sum:integer; m:type_matrix; begin m.lin:=v.size;   (* the number of columns is equal to the greatest element *) m.col:=0; for i:=1 to v.size do if v.vector[i] > m.col then m.col:=v.vector[i];   (* initializing the matrix *) for j:=1 to m.lin do begin k:=1; for i:=m.col downto 1 do begin if v.vector[j] >= k then m.matrix[i,j]:=TRUE else m.matrix[i,j]:=FALSE; k:=k+1; end; end;   (* Sort the matrix *) for i:=1 to m.col do begin (* Count the beads and set the line equal FALSE *) sum:=0; for j:=1 to m.lin do begin if m.matrix[i,j] then sum:=sum+1; m.matrix[i,j]:=FALSE; end;   (* The line receives the bead sorted *) for j:=m.lin downto m.lin-sum+1 do m.matrix[i,j]:=TRUE; end;   (* Convert the sorted bead matrix to a sorted vector *) for j:=1 to m.lin do begin v.vector[j]:=0; i:=m.col; while (m.matrix[i,j] = TRUE)and(i>=1) do begin v.vector[j]+=1; i:=i-1; end; end; end;   procedure print_vector(var v:type_vector); var i:integer; begin for i:=1 to v.size do write(v.vector[i],' '); writeln; end;   var i:integer; v:type_vector; begin writeln('How many numbers do you want to sort?'); readln(v.size); writeln('Write the numbers:');   for i:=1 to v.size do read(v.vector[i]);   writeln('Before sort:'); print_vector(v);   BeadSort(v);   writeln('After sort:'); print_vector(v); end.    
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Ksh
Ksh
#!/bin/ksh   # cocktail shaker sort   # # Variables: # integer TRUE=1 integer FALSE=0 typeset -a arr=( 5 -1 101 -4 0 1 8 6 2 3 )   # # Functions: # function _swap { typeset _i ; integer _i=$1 typeset _j ; integer _j=$2 typeset _array ; nameref _array="$3" typeset _swapped ; nameref _swapped=$4   typeset _tmp ; _tmp=${_array[_i]} _array[_i]=${_array[_j]} _array[_j]=${_tmp} _swapped=$TRUE }   ###### # main # ######   print "( ${arr[*]} )"   integer i j integer swapped=$TRUE while (( swapped )); do swapped=$FALSE for (( i=0 ; i<${#arr[*]}-2 ; i++ , j=i+1 )); do (( arr[i] > arr[j] )) && _swap ${i} ${j} arr swapped done (( ! swapped )) && break   swapped=$FALSE for (( i=${#arr[*]}-2 ; i>0 ; i-- , j=i+1 )); do (( arr[i] > arr[j] )) && _swap ${i} ${j} arr swapped done done   print "( ${arr[*]} )"
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Perl
Perl
#! /usr/bin/perl use strict;   sub counting_sort { my ($a, $min, $max) = @_;   my @cnt = (0) x ($max - $min + 1); $cnt[$_ - $min]++ foreach @$a;   my $i = $min; @$a = map {($i++) x $_} @cnt; }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#ALGOL_W
ALGOL W
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.
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#APL
APL
X←63 92 51 92 39 15 43 89 36 69 X[⍋X] 15 36 39 43 51 63 69 89 92 92
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#AppleScript
AppleScript
(* Shell sort Algorithm: Donald Shell, 1959. *)   on ShellSort(theList, l, r) script o property lst : theList end script   set listLength to (count theList) if (listLength > 1) then -- Convert negative and/or transposed range indices. if (l < 0) then set l to listLength + l + 1 if (r < 0) then set r to listLength + r + 1 if (l > r) then set {l, r} to {r, l}   -- Do the sort. set stepSize to (r - l + 1) div 2 repeat while (stepSize > 0) repeat with i from (l + stepSize) to r set currentValue to item i of o's lst repeat with j from (i - stepSize) to l by -stepSize set thisValue to item j of o's lst if (currentValue < thisValue) then set item (j + stepSize) of o's lst to thisValue else set j to j + stepSize exit repeat end if end repeat if (j < i) then set item j of o's lst to currentValue end repeat set stepSize to (stepSize / 2.2) as integer end repeat end if   return -- nothing. The input list has been sorted in place. end ShellSort property sort : ShellSort   -- Test code: sort items 1 thru -1 (ie. all) of a list of strings, treating numeric portions numerically. set theList to {"1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", ¬ "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0"} considering numeric strings sort(theList, 1, -1) end considering return theList
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#C.23
C#
using System; using System.Linq; using System.Collections.Generic;   public class Test { public static void Main() { var list = new List<int>{ 7, 6, 5, 4, 3, 2, 1, 0 }; list.SortSublist(6, 1, 7); Console.WriteLine(string.Join(", ", list)); } }   public static class Extensions { public static void SortSublist<T>(this List<T> list, params int[] indices) where T : IComparable<T> { var sublist = indices.OrderBy(i => i) .Zip(indices.Select(i => list[i]).OrderBy(v => v), (Index, Value) => new { Index, Value });   foreach (var entry in sublist) { list[entry.Index] = entry.Value; } }   }
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Java
Java
import java.util.Arrays; import java.util.Comparator;   public class RJSortStability {   public static void main(String[] args) { String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", };   String[] cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String city : cn) { System.out.println(city); }   // sort by city Arrays.sort(cn, new Comparator<String>() { public int compare(String lft, String rgt) { return lft.substring(4).compareTo(rgt.substring(4)); } });   System.out.println("\nAfter sort on city:"); for (String city : cn) { System.out.println(city); }   cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String city : cn) { System.out.println(city); }   // sort by country Arrays.sort(cn, new Comparator<String>() { public int compare(String lft, String rgt) { return lft.substring(0, 2).compareTo(rgt.substring(0, 2)); } });   System.out.println("\nAfter sort on country:"); for (String city : cn) { System.out.println(city); }   System.out.println(); } }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#PureBasic
PureBasic
EnableExplicit   Procedure lexOrder(n, Array ints(1)) Define first = 1, last = n, k = n, i If n < 1 first = n last = 1 k = 2 - n EndIf Dim strs.s(k - 1) For i = first To last strs(i - first) = Str(i) Next SortArray(strs(), #PB_Sort_Ascending) For i = 0 To k - 1 ints(i) = Val(Strs(i)) Next EndProcedure   If OpenConsole() PrintN(~"In lexicographical order:\n") Define i, j, n, k For i = 0 To 4 Read n k = n If n < 1 k = 2 - n EndIf Dim ints(k - 1) lexOrder(n, ints()) Define.s ns = RSet(Str(n), 3) Print(ns + ": [") For j = 0 To k - 1 Print(Str(ints(j)) + " ") Next j PrintN(~"\b]") Next i Input() End   DataSection Data.i 0, 5, 13, 21, -22 EndDataSection EndIf
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Java
Java
  import java.util.Comparator; import java.util.stream.Stream;   class Box { public int weightKg;   Box(final int weightKg) { this.weightKg = weightKg; } }   public class Sort3Vars { public static void main(String... args) { int iA = 21; int iB = 11; int iC = 82; int[] sortedInt = Stream.of(iA, iB, iC).sorted().mapToInt(Integer::intValue).toArray(); iA = sortedInt[0]; iB = sortedInt[1]; iC = sortedInt[2]; System.out.printf("Sorted values: %d %d %d%n", iA, iB, iC);   String sA = "s21"; String sB = "s11"; String sC = "s82"; Object[] sortedStr = Stream.of(sA, sB, sC).sorted().toArray(); sA = (String) sortedStr[0]; sB = (String) sortedStr[1]; sC = (String) sortedStr[2]; System.out.printf("Sorted values: %s %s %s%n", sA, sB, sC);   Box bA = new Box(200); Box bB = new Box(12); Box bC = new Box(143); // Provides a comparator for Box instances Object[] sortedBox = Stream.of(bA, bB, bC).sorted(Comparator.comparingInt(a -> a.weightKg)).toArray(); bA = (Box) sortedBox[0]; bB = (Box) sortedBox[1]; bC = (Box) sortedBox[2]; System.out.printf("Sorted Boxes: %dKg %dKg %dKg%n", bA.weightKg, bB.weightKg, bC.weightKg); } }  
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Fantom
Fantom
  class Main { public static Void main () { // sample strings from Lisp example strs := ["Cat", "apple", "Adam", "zero", "Xmas", "quit", "Level", "add", "Actor", "base", "butter"]   sorted := strs.dup // make a copy of original list sorted.sort |Str a, Str b -> Int| // sort using custom comparator { if (b.size == a.size) // if size is same return a.compareIgnoreCase(b) // then sort in ascending lexicographic order, ignoring case else return b.size <=> a.size // else sort in descending size order } echo ("Started with : " + strs.join(" ")) echo ("Finished with: " + sorted.join(" ")) } }  
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Python
Python
>>> def combsort(input): gap = len(input) swaps = True while gap > 1 or swaps: gap = max(1, int(gap / 1.25)) # minimum gap is 1 swaps = False for i in range(len(input) - gap): j = i+gap if input[i] > input[j]: input[i], input[j] = input[j], input[i] swaps = True     >>> y = [88, 18, 31, 44, 4, 0, 8, 81, 14, 78, 20, 76, 84, 33, 73, 75, 82, 5, 62, 70] >>> combsort(y) >>> assert y == sorted(y) >>> y [0, 4, 5, 8, 14, 18, 20, 31, 33, 44, 62, 70, 73, 75, 76, 78, 81, 82, 84, 88] >>>
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Pascal
Pascal
program bogosort;   const max = 5; type list = array [1..max] of integer;   { Print a list } procedure printa(a: list); var i: integer; begin for i := 1 to max do write(a[i], ' '); writeln end;   { Knuth shuffle } procedure shuffle(var a: list); var i,k,tmp: integer; begin for i := max downto 2 do begin k := random(i) + 1; if (a[i] <> a[k]) then begin tmp := a[i]; a[i] := a[k]; a[k] := tmp end end end;   { Check for sorted list } function sorted(a: list): boolean; var i: integer; begin sorted := True; for i := 2 to max do if (a[i - 1] > a[i]) then begin sorted := False; exit end end;   { Bogosort } procedure bogo(var a: list); var i: integer; begin i := 1; randomize; write(i,': '); printa(a); while not sorted(a) do begin shuffle(a); i := i + 1; write(i,': '); printa(a) end end;   { Test and display } var a: list; i: integer;   begin for i := 1 to max do a[i] := (max + 1) - i; bogo(a); end.
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. BUBBLESORT. AUTHOR. DAVE STRATFORD. DATE-WRITTEN. MARCH 2010. INSTALLATION. HEXAGON SYSTEMS LIMITED.   ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. ICL VME. OBJECT-COMPUTER. ICL VME.   INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT FA-INPUT-FILE ASSIGN FL01. SELECT FB-OUTPUT-FILE ASSIGN FL02.   DATA DIVISION. FILE SECTION.   FD FA-INPUT-FILE. 01 FA-INPUT-REC. 03 FA-DATA PIC S9(6).   FD FB-OUTPUT-FILE. 01 FB-OUTPUT-REC PIC S9(6).   WORKING-STORAGE SECTION. 01 WA-IDENTITY. 03 WA-PROGNAME PIC X(10) VALUE "BUBBLESORT". 03 WA-VERSION PIC X(6) VALUE "000001".   01 WB-TABLE. 03 WB-ENTRY PIC 9(8) COMP SYNC OCCURS 100000 INDEXED BY WB-IX-1.   01 WC-VARS. 03 WC-SIZE PIC S9(8) COMP SYNC. 03 WC-TEMP PIC S9(8) COMP SYNC. 03 WC-END PIC S9(8) COMP SYNC. 03 WC-LAST-CHANGE PIC S9(8) COMP SYNC.   01 WF-CONDITION-FLAGS. 03 WF-EOF-FLAG PIC X. 88 END-OF-FILE VALUE "Y". 03 WF-EMPTY-FILE-FLAG PIC X. 88 EMPTY-FILE VALUE "Y".   PROCEDURE DIVISION. A-MAIN SECTION. A-000. PERFORM B-INITIALISE. IF NOT EMPTY-FILE PERFORM C-SORT. PERFORM D-FINISH.   A-999. STOP RUN.   B-INITIALISE SECTION. B-000. DISPLAY "*** " WA-PROGNAME " VERSION " WA-VERSION " STARTING ***".   MOVE ALL "N" TO WF-CONDITION-FLAGS. OPEN INPUT FA-INPUT-FILE. SET WB-IX-1 TO 0.   READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG WF-EMPTY-FILE-FLAG.   PERFORM BA-READ-INPUT UNTIL END-OF-FILE.   CLOSE FA-INPUT-FILE.   SET WC-SIZE TO WB-IX-1.   B-999. EXIT.   BA-READ-INPUT SECTION. BA-000. SET WB-IX-1 UP BY 1. MOVE FA-DATA TO WB-ENTRY(WB-IX-1).   READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG.   BA-999. EXIT.   C-SORT SECTION. C-000. DISPLAY "SORT STARTING".   MOVE WC-SIZE TO WC-END. PERFORM E-BUBBLE UNTIL WC-END = 1.   DISPLAY "SORT FINISHED".   C-999. EXIT.   D-FINISH SECTION. D-000. OPEN OUTPUT FB-OUTPUT-FILE. SET WB-IX-1 TO 1.   PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE.   CLOSE FB-OUTPUT-FILE.   DISPLAY "*** " WA-PROGNAME " FINISHED ***".   D-999. EXIT.   DA-WRITE-OUTPUT SECTION. DA-000. WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1). SET WB-IX-1 UP BY 1.   DA-999. EXIT.   E-BUBBLE SECTION. E-000. MOVE 1 TO WC-LAST-CHANGE.   PERFORM F-PASS VARYING WB-IX-1 FROM 1 BY 1 UNTIL WB-IX-1 = WC-END.   MOVE WC-LAST-CHANGE TO WC-END.   E-999. EXIT.   F-PASS SECTION. F-000. IF WB-ENTRY(WB-IX-1) > WB-ENTRY(WB-IX-1 + 1) SET WC-LAST-CHANGE TO WB-IX-1 MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP MOVE WB-ENTRY(WB-IX-1 + 1) TO WB-ENTRY(WB-IX-1) MOVE WC-TEMP TO WB-ENTRY(WB-IX-1 + 1).   F-999. EXIT.  
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Java
Java
public static void gnomeSort(int[] a) { int i=1; int j=2;   while(i < a.length) { if ( a[i-1] <= a[i] ) { i = j; j++; } else { int tmp = a[i-1]; a[i-1] = a[i]; a[i--] = tmp; i = (i==0) ? j++ : i; } } }
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Perl
Perl
sub beadsort { my @data = @_;   my @columns; my @rows;   for my $datum (@data) { for my $column ( 0 .. $datum-1 ) { ++ $rows[ $columns[$column]++ ]; } }   return reverse @rows; }   beadsort 5, 7, 1, 3, 1, 1, 20;  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Haxe
Haxe
class CocktailSort { @:generic public static function sort<T>(arr:Array<T>) { var swapped = false; do { swapped = false; for (i in 0...(arr.length - 1)) { if (Reflect.compare(arr[i], arr[i + 1]) > 0) { var temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; swapped = true; } } if (!swapped) break; swapped = false; var i = arr.length - 2; while (i >= 0) { if (Reflect.compare(arr[i], arr[i + 1]) > 0) { var temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; swapped = true; } i--; } } while (swapped); } }   class Main { static function main() { var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0.0, -4.1, -9.5]; var stringArray = ['We', 'hold', 'these', 'truths', 'to', 'be', 'self-evident', 'that', 'all', 'men', 'are', 'created', 'equal']; Sys.println('Unsorted Integers: ' + integerArray); CocktailSort.sort(integerArray); Sys.println('Sorted Integers: ' + integerArray); Sys.println('Unsorted Floats: ' + floatArray); CocktailSort.sort(floatArray); Sys.println('Sorted Floats: ' + floatArray); Sys.println('Unsorted Strings: ' + stringArray); CocktailSort.sort(stringArray); Sys.println('Sorted Strings: ' + stringArray); } }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Phix
Phix
with javascript_semantics function countingSort(sequence array, integer mina, maxa) sequence count = repeat(0,maxa-mina+1) array = deep_copy(array) for i=1 to length(array) do count[array[i]-mina+1] += 1 end for integer z = 1 for i=mina to maxa do for j=1 to count[i-mina+1] do array[z] := i z += 1 end for end for return array end function sequence s = {5, 3, 1, 7, 4, 1, 1, 20} ?countingSort(s,min(s),max(s))
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#11l
11l
V neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] [Int] exists V lastNumber = 0 V wid = 0 V hei = 0   F find_next(pa, x, y, z) L(i) 4 V a = x + :neighbours[i][0] V b = y + :neighbours[i][1] I a C -1 <.< :wid & b C -1 <.< :hei I pa[a][b] == z R (a, b) R (-1, -1)   F find_solution(&pa, x, y, z) I z > :lastNumber R 1 I :exists[z] == 1 V s = find_next(pa, x, y, z) I s[0] < 0 R 0 R find_solution(&pa, s[0], s[1], z + 1)   L(i) 4 V a = x + :neighbours[i][0] V b = y + :neighbours[i][1] I a C -1 <.< :wid & b C -1 <.< :hei I pa[a][b] == 0 pa[a][b] = z V r = find_solution(&pa, a, b, z + 1) I r == 1 R 1 pa[a][b] = 0 R 0   F solve(pz, w, h)  :lastNumber = w * h  :wid = w  :hei = h  :exists = [0] * (:lastNumber + 1)   V pa = [[0] * h] * w V st = pz.split(‘ ’) V idx = 0   L(j) 0 .< h L(i) 0 .< w I st[idx] == ‘.’ idx++ E pa[i][j] = Int(st[idx])  :exists[pa[i][j]] = 1 idx++   V x = 0 V y = 0 V t = w * h + 1 L(j) 0 .< h L(i) 0 .< w I pa[i][j] != 0 & pa[i][j] < t t = pa[i][j] x = i y = j   R (find_solution(&pa, x, y, t + 1), pa)   F show_result(r) I r[0] == 1 L(j) 0 .< :hei L(i) 0 .< :wid print(‘ #02’.format(r[1][i][j]), end' ‘’) print() E print(‘No Solution!’)   print()   V r = solve(‘. . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17’"" ‘ . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .’, 9, 9) show_result(r) r = solve(‘. . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37’"" ‘ . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .’, 9, 9) show_result(r) r = solve(‘17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55’"" ‘ . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45’, 9, 9) show_result(r)
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#AppleScript
AppleScript
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
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#AutoHotkey
AutoHotkey
; based on http://www.rosettacode.org/wiki/Sorting_algorithms/Quicksort#AutoHotkey OidQuickSort(a, Delim:=".", index:=1){ if (a.Count() <= 1) return a Less := [], Equal := [], More := [] Pivot := StrSplit(a[1], Delim)[index] for k, v in a { x := StrSplit(v, Delim)[index] if (x < Pivot) less.InsertAt(1, v) else if (x > Pivot) more.InsertAt(1, v) else Equal.InsertAt(1, v) } Equal := OidQuickSort(Equal, Delim, index+1) Less := OidQuickSort(Less) Out := OidQuickSort(More) if (Equal.Count()) Out.InsertAt(1, Equal*) ; InsertAt all values of Equal at index 1 if (Less.Count()) Out.InsertAt(1, Less*) ; InsertAt all values of Less at index 1 return Out }
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <iterator> #include <vector>   template <typename ValueIterator, typename IndicesIterator> void sortDisjoint(ValueIterator valsBegin, IndicesIterator indicesBegin, IndicesIterator indicesEnd) { std::vector<int> temp;   for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i) temp.push_back(valsBegin[*i]); // extract   std::sort(indicesBegin, indicesEnd); // sort std::sort(temp.begin(), temp.end()); // sort a C++ container   std::vector<int>::const_iterator j = temp.begin(); for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i, ++j) valsBegin[*i] = *j; // replace }     int main() { int values[] = { 7, 6, 5, 4, 3, 2, 1, 0 }; int indices[] = { 6, 1, 7 };   sortDisjoint(values, indices, indices+3);   std::copy(values, values + 8, std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n";   return 0; }
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#JavaScript
JavaScript
ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] print(ary);   ary.sort(function(a,b){return (a[1]<b[1] ? -1 : (a[1]>b[1] ? 1 : 0))}); print(ary);   /* a stable sort will output ["US", "Birmingham"] before ["UK", "Birmingham"] */
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#jq
jq
[["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] | sort_by(.[1])
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Python
Python
n=13 print(sorted(range(1,n+1), key=str))
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Quackery
Quackery
[ [] swap times [ i^ 1+ number$ nested join ] sort$ [] swap witheach [ $->n drop join ] ] is task ( n --> [ )   13 task echo
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Racket
Racket
#lang racket   (define (lex-sort n) (sort (if (< 0 n) (range 1 (add1 n)) (range n 2)) string<? #:key number->string))   (define (show n) (printf "~a: ~a\n" n (lex-sort n)))   (show 0) (show 1) (show 5) (show 13) (show 21) (show -22)
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Raku
Raku
sub lex (Real $n, $step = 1) { ($n < 1 ?? ($n, * + $step …^ * > 1) !! ($n, * - $step …^ * < 1)).sort: ~* }   # TESTING for 13, 21, -22, (6, .333), (-4, .25), (-5*π, e) { my ($bound, $step) = |$_, 1; say "Boundary:$bound, Step:$step >> ", lex($bound, $step).join: ', '; }
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#JavaScript
JavaScript
const printThree = (note, [a, b, c], [a1, b1, c1]) => { console.log(`${note} ${a} is: ${a1} ${b} is: ${b1} ${c} is: ${c1} `); }; const sortThree = () => {   let a = 'lions, tigers, and'; let b = 'bears, oh my!'; let c = '(from the "Wizard of OZ")'; printThree('Before Sorting', ['a', 'b', 'c'], [a, b, c]);   [a, b, c] = [a, b, c].sort(); printThree('After Sorting', ['a', 'b', 'c'], [a, b, c]);   let x = 77444; let y = -12; let z = 0; printThree('Before Sorting', ['x', 'y', 'z'], [x, y, z]);   [x, y, z] = [x, y, z].sort(); printThree('After Sorting', ['x', 'y', 'z'], [x, y, z]); }; sortThree();  
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Fortran
Fortran
module sorts_with_custom_comparator implicit none contains subroutine a_sort(a, cc) character(len=*), dimension(:), intent(inout) :: a interface integer function cc(a, b) character(len=*), intent(in) :: a, b end function cc end interface   integer :: i, j, increment character(len=max(len(a), 10)) :: temp   increment = size(a) / 2 do while ( increment > 0 ) do i = increment+1, size(a) j = i temp = a(i) do while ( j >= increment+1 .and. cc(a(j-increment), temp) > 0) a(j) = a(j-increment) j = j - increment end do a(j) = temp end do if ( increment == 2 ) then increment = 1 else increment = increment * 5 / 11 end if end do end subroutine a_sort end module sorts_with_custom_comparator
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#R
R
  comb.sort<-function(a){ gap<-length(a) swaps<-1 while(gap>1 & swaps==1){ gap=floor(gap/1.3) if(gap<1){ gap=1 } swaps=0 i=1 while(i+gap<=length(a)){ if(a[i]>a[i+gap]){ a[c(i,i+gap)] <- a[c(i+gap,i)] swaps=1 } i<-i+1 } } return(a) }    
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Perl
Perl
use List::Util qw(shuffle);   sub bogosort {my @l = @_; @l = shuffle(@l) until in_order(@l); return @l;}   sub in_order {my $last = shift; foreach (@_) {$_ >= $last or return 0; $last = $_;} return 1;}
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Common_Lisp
Common Lisp
(defun bubble-sort (sequence &optional (compare #'<)) "sort a sequence (array or list) with an optional comparison function (cl:< is the default)" (loop with sorted = nil until sorted do (setf sorted t) (loop for a below (1- (length sequence)) do (unless (funcall compare (elt sequence a) (elt sequence (1+ a))) (rotatef (elt sequence a) (elt sequence (1+ a))) (setf sorted nil)))))
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#JavaScript
JavaScript
function gnomeSort(a) { function moveBack(i) { for( ; i > 0 && a[i-1] > a[i]; i--) { var t = a[i]; a[i] = a[i-1]; a[i-1] = t; } } for (var i = 1; i < a.length; i++) { if (a[i-1] > a[i]) moveBack(i); } return a; }
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Phix
Phix
with javascript_semantics function beadsort(sequence a) sequence poles = repeat(0,max(a)) for i=1 to length(a) do poles[1..a[i]] = sq_add(poles[1..a[i]],1) end for a[1..$] = 0 for i=1 to length(poles) do a[1..poles[i]] = sq_add(a[1..poles[i]],1) end for return a end function ?beadsort({5, 3, 1, 7, 4, 1, 1, 20})
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string demosort(cocktailsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") end   procedure cocktailsort(X,op) #: return sorted list local i,swapped   op := sortop(op,X) # select how and what we sort   swapped := 1 repeat # translation of pseudo code. Contractions used to eliminate second loop. every (if /swapped then break break else swapped := &null & next) | ( i := 1 to *X-1) | (if /swapped then break break else swapped := &null & next) | ( i := *X-1 to 1 by -1) do if op(X[i+1],X[i]) then X[i+1] :=: X[swapped := i] return X end
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#11l
11l
T Employee String name, category   F (name, category) .name = name .category = category   V employees = [ Employee(‘David’, ‘Manager’), Employee(‘Alice’, ‘Sales’), Employee(‘Joanna’, ‘Director’), Employee(‘Henry’, ‘Admin’), Employee(‘Tim’, ‘Sales’), Employee(‘Juan’, ‘Admin’) ]   employees.sort(key' e -> e.name)   L(e) employees print(‘#<6 : #.’.format(e.name, e.category))
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#PHP
PHP
<?php   function counting_sort(&$arr, $min, $max) { $count = array(); for($i = $min; $i <= $max; $i++) { $count[$i] = 0; }   foreach($arr as $number) { $count[$number]++; } $z = 0; for($i = $min; $i <= $max; $i++) { while( $count[$i]-- > 0 ) { $arr[$z++] = $i; } } }
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#AutoHotkey
AutoHotkey
SolveNumbrix(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){ if (R&&C) ; if neighbors (not first iteration) { Grid[R, C] := ">" num ; place num in current neighbor and mark it visited ">" row:=R, col:=C ; move to current neighbor }   num++ ; increment num if (num=max) ; if reached end return map(Grid) ; return solution   if locked[num] ; if current num is a locked value { row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 ; find row of num col := StrSplit((StrSplit(locked[num], ",").1) , ":").2 ; find col of num if SolveNumbrix(Grid, Locked, Max, row, col, num) ; solve for current location and value return map(Grid) ; if solved, return solution } else { for each, value in StrSplit(Neighbor(row,col), ",") { R := StrSplit(value, ":").1 C := StrSplit(value, ":").2   if (Grid[R,C] = "") ; a hole or out of bounds || InStr(Grid[R, C], ">") ; visited || Locked[num+1] && !(Locked[num+1]~= "\b" R ":" C "\b") ; not neighbor of locked[num+1] || Locked[num-1] && !(Locked[num-1]~= "\b" R ":" C "\b") ; not neighbor of locked[num-1] || Locked[num] ; locked value || Locked[Grid[R, C]] ; locked cell continue   if SolveNumbrix(Grid, Locked, Max, row, col, num, R, C) ; solve for current location, neighbor and value return map(Grid) ; if solved, return solution } } num-- ; step back for i, line in Grid for j, element in line if InStr(element, ">") && (StrReplace(element, ">") >= num) Grid[i, j] := 0 } ;-------------------------------- ;-------------------------------- ;-------------------------------- Neighbor(row,col){ return row-1 ":" col . "," row+1 ":" col . "," row ":" col+1 . "," row ":" col-1 } ;-------------------------------- map(Grid){ for i, row in Grid { for j, element in row line .= (A_Index > 1 ? "`t" : "") . element map .= (map<>""?"`n":"") line line := "" } return StrReplace(map, ">") }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#ARM_Assembly
ARM Assembly
    /* 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"  
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#AWK
AWK
  # syntax: GAWK -f SORT_A_LIST_OF_OBJECT_IDENTIFIERS.AWK # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { width = 10 oid_arr[++n] = "1.3.6.1.4.1.11.2.17.19.3.4.0.10" oid_arr[++n] = "1.3.6.1.4.1.11.2.17.5.2.0.79" oid_arr[++n] = "1.3.6.1.4.1.11.2.17.19.3.4.0.4" oid_arr[++n] = "1.3.6.1.4.1.11150.3.4.0.1" oid_arr[++n] = "1.3.6.1.4.1.11.2.17.19.3.4.0.1" oid_arr[++n] = "1.3.6.1.4.1.11150.3.4.0" # oid_arr[++n] = "1.11111111111.1" # un-comment to test error for (i=1; i<=n; i++) { str = "" for (j=1; j<=split(oid_arr[i],arr2,"."); j++) { str = sprintf("%s%*s.",str,width,arr2[j]) if ((leng = length(arr2[j])) > width) { printf("error: increase sort key width from %d to %d for entry %s\n",width,leng,oid_arr[i]) exit(1) } } arr3[str] = "" } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i in arr3) { str = i gsub(/ /,"",str) sub(/\.$/,"",str) printf("%s\n",str) } exit(0) }  
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#Clojure
Clojure
(defn disjoint-sort [coll idxs] (let [val-subset (keep-indexed #(when ((set idxs) %) %2) coll) replacements (zipmap (set idxs) (sort val-subset))] (apply assoc coll (flatten (seq replacements)))))
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Julia
Julia
julia> A = [("UK", "London"), ("US", "New York"), ("US", "Birmingham"), ("UK", "Birmingham")]; julia> sort(A, by=x -> x[2]) 4-element Array{(ASCIIString,ASCIIString),1}: ("US","Birmingham") ("UK","Birmingham") ("UK","London") ("US","New York")
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Kotlin
Kotlin
// version 1.1.51   fun main(args: Array<String>) { val cities = listOf("UK London", "US New York", "US Birmingham", "UK Birmingham") println("Original  : $cities") // sort by country println("By country : ${cities.sortedBy { it.take(2) } }") // sort by city println("By city  : ${cities.sortedBy { it.drop(3) } }") }
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Lasso
Lasso
//Single param array: array->sort   //An array of pairs, order by the right hand element of the pair: with i in array order by #i->second do => { … }   //The array can also be ordered by multiple values: with i in array order by #i->second, #i->first do => { … }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#REXX
REXX
/*REXX pgm displays a horizontal list of a range of numbers sorted lexicographically.*/ parse arg LO HI INC . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= 13 /* " " " " " " */ if INC=='' | INC=="," then INC= 1 /* " " " " " " */ #= 0 /*for actual sort, start array with 1.*/ do j=LO to HI by INC /*construct an array from LO to HI.*/ #= # + 1; @.#= j / 1 /*bump counter; define array element. */ end /*j*/ /* [↑] Also, normalize the element #. */ call Lsort # /*sort numeric array with a simple sort*/ $= /*initialize a horizontal numeric list.*/ do k=1 for #; $= $','@.k /*construct " " " */ end /*k*/ /* [↑] prefix each number with a comma*/ /* [↓] display a continued SAY text.*/ say 'for ' LO"──►"HI ' by ' INC " (inclusive), " # , ' elements sorted lexicographically:' say '['strip($, "L", ',')"]" /*strip leading comma, bracket the list*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Lsort: procedure expose @.; parse arg n; m= n-1 /*N: is the number of @ array elements.*/ do m=m by -1 until ok; ok= 1 /*keep sorting the @ array until done.*/ do j=1 for m; k= j+1; if @.j>>@.k then parse value @.j @.k 0 with @.k @.j ok end /*j*/ /* [↑] swap 2 elements, flag as ¬done.*/ end /*m*/; return
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Ring
Ring
  # Project : Lexicographical numbers   lex = 1:13 strlex = list(len(lex)) for n = 1 to len(lex) strlex[n] = string(lex[n]) next strlex = sort(strlex) see "Lexicographical numbers = " showarray(strlex)   func showarray(vect) see "[" svect = "" for n = 1 to len(vect) svect = svect + vect[n] + "," next svect = left(svect, len(svect) - 1) see svect + "]" + nl  
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#jq
jq
def example1: {x: "lions, tigers, and", y: "bears, oh my", z: "(from the \"Wizard of OZ\")" };   def example2: {x: 77444, y: -12, z: 0 };
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Jsish
Jsish
#!/usr/bin/env jsish /* Sort three variables, in Jsish. semi-colon start/end for unit test echo */   var x = 'lions, tigers, and'; var y = 'bears, oh my!'; var z = '(from the "Wizard of OZ")';   var arr = [x,y,z]; arr = arr.sort();   ;'As strings, before:'; ;x; ;y; ;z;   x = arr.shift(); y = arr.shift(); z = arr.shift();   ;'x,y,z after:'; ;x; ;y; ;z;   x = 77444; y = -12; z = 0;   arr = [x,y,z]; arr = arr.sort();   ;'As numbers before:'; ;x; ;y; ;z;   x = arr.shift(); y = arr.shift(); z = arr.shift();   ;'x,y,z after:'; ;x; ;y; ;z;   ;'Mixed, integer, float, string'; x = 3.14159; y = 2; z = '1 string'; ;x; ;y; ;z; arr = [x,y,z].sort(); x = arr.shift(); y = arr.shift(); z = arr.shift(); ;'x,y,z after:'; ;x; ;y; ;z;     /* =!EXPECTSTART!= 'As strings, before:' x ==> lions, tigers, and y ==> bears, oh my! z ==> (from the "Wizard of OZ") 'x,y,z after:' x ==> (from the "Wizard of OZ") y ==> bears, oh my! z ==> lions, tigers, and 'As numbers before:' x ==> 77444 y ==> -12 z ==> 0 'x,y,z after:' x ==> -12 y ==> 0 z ==> 77444 'Mixed, integer, float, string' x ==> 3.14159 y ==> 2 z ==> 1 string 'x,y,z after:' x ==> 2 y ==> 3.14159 z ==> 1 string =!EXPECTEND!= */
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#FreeBASIC
FreeBASIC
' version 23-10-2016 ' compile with: fbc -s console   #Include Once "crt/stdlib.bi" ' for qsort   Function mycmp Cdecl (s1 As Any Pointer, s2 As Any Pointer) As Long   ' -1 no swap first element before second element ' 0 no swap needed, don't care ' 1 swap first element after second element   Dim As String str1 = *Cast(String Ptr, s1) Dim As String str2 = *Cast(String Ptr, s2)   Dim As Long l1 = Len(str1), l2 = Len(str2) If (l1 > l2) Then Return -1 ' descending If (l1 < l2) Then Return 1 '   ' there equal length, sort ascending If UCase(str1) = UCase(str2) Then If str1 > str2 Then Return 1 Else If UCase(str1) > UCase(str2) Then Return 1 End If   Return 0   End Function   ' ------=< MAIN >=------   Dim As String words(0 To ...) = {"Here", "are", "some", "sample", _ "strings", "to", "be", "sorted" }   Dim As ULong array_size = UBound(words) - LBound(words) + 1   qsort(@words(0), array_size, SizeOf(String), @mycmp)   For i As Integer = 0 To UBound(words) Print words(i) Next Print   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Racket
Racket
  #lang racket (require (only-in srfi/43 vector-swap!))   (define (comb-sort xs) (define (ref i) (vector-ref xs i)) (define (swap i j) (vector-swap! xs i j)) (define (new gap) (max 1 (exact-floor (/ gap 1.25)))) (define size (vector-length xs)) (let loop ([gap size] [swaps 0]) (unless (and (= gap 1) (= swaps 0)) (loop (new gap) (for/fold ([swaps 0]) ([i (in-range 0 (- size gap))]) (cond [(> (ref i) (ref (+ i gap))) (swap i (+ i gap)) (+ swaps 1)] [swaps]))))) xs)  
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Phix
Phix
with javascript_semantics function inOrder(sequence s) return s==sort(deep_copy(s)) -- <snigger> end function function bogosort(sequence s) while not inOrder(s) do ? s s = shuffle(s) end while return s end function ? bogosort(shuffle({1,2,3,4,5,6}))
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Cowgol
Cowgol
include "cowgol.coh";   # Comparator interface, on the model of C, i.e: # foo < bar => -1, foo == bar => 0, foo > bar => 1 typedef CompRslt is int(-1, 1); interface Comparator(foo: intptr, bar: intptr): (rslt: CompRslt);   # Bubble sort an array of pointer-sized integers given a comparator function # (This is the closest you can get to polymorphism in Cowgol). sub bubbleSort(A: [intptr], len: intptr, comp: Comparator) is loop var swapped: uint8 := 0; var i: intptr := 1; var a := @next A; while i < len loop if comp([@prev a], [a]) == 1 then var t := [a]; [a] := [@prev a]; [@prev a] := t; swapped := 1; end if; a := @next a; i := i + 1; end loop; if swapped == 0 then return; end if; end loop; end sub;   # Test: sort a list of numbers sub NumComp implements Comparator is # Compare the inputs as numbers if foo < bar then rslt := -1; elseif foo > bar then rslt := 1; else rslt := 0; end if; end sub;   # Numbers var numbers: intptr[] := { 65,13,4,84,29,5,96,73,5,11,17,76,38,26,44,20,36,12,44,51,79,8,99,7,19,95,26 };   # Sort the numbers in place bubbleSort(&numbers as [intptr], @sizeof numbers, NumComp);   # Print the numbers (hopefully in order) var i: @indexof numbers := 0; while i < @sizeof numbers loop print_i32(numbers[i] as uint32); print_char(' '); i := i + 1; end loop; print_nl();
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#jq
jq
# As soon as "condition" is true, then emit . and stop: def do_until(condition; next): def u: if condition then . else (next|u) end; u;   # input: an array def gnomeSort: def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;   length as $length # state: [i, j, ary] | [1, 2, .] | do_until( .[0] >= $length; .[0] as $i | .[1] as $j | .[2] # for descending sort, use >= for comparison | if .[$i-1] <= .[$i] then [$j, $j + 1, .] else swap( $i-1; $i) | ($i - 1) as $i | if $i == 0 then [$j, $j + 1, .] else [$i, $j, .] end end ) | .[2];
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#PHP
PHP
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1);   array_unshift($arr, NULL); // array_map(NULL, $arr[0], $arr[1], ...) $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); }   function beadsort($arr) { foreach ($arr as $e) $poles []= array_fill(0, $e, 1); return array_map('count', columns(columns($poles))); }   print_r(beadsort(array(5,3,1,7,4,1,1))); ?>
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Io
Io
List do ( cocktailSortInPlace := method( start := 0 end := size - 2   loop( swapped := false   for(idx, start, end, if(at(idx) > at(idx + 1), swapped := true swapIndices(idx, idx + 1) ) )   if(swapped not, break, end := end - 1)   for (idx, end, start, -1, if(at(idx) > at(idx + 1), swapped := true swapIndices(idx, idx + 1) ) )   if(swapped not, break, start := start + 1) ) self) )   l := list(2, 3, 4, 5, 1) l cocktailSortInPlace println # ==> list(1, 2, 3, 4, 5)
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program shellSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Structures */ /********************************************/ /* city structure */ .struct 0 city_name: // .struct city_name + 8 // string pointer city_habitants: // .struct city_habitants + 8 // integer city_end:   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Name : @ number habitants : @ \n" szMessSortHab: .asciz "Sort table for number of habitants :\n" szMessSortName: .asciz "Sort table for name of city :\n" szCarriageReturn: .asciz "\n"   // cities name szCeret: .asciz "Ceret" szMaureillas: .asciz "Maureillas" szTaillet: .asciz "Taillet" szReynes: .asciz "Reynes" szVives: .asciz "Vivés" szBoulou: .asciz "Le Boulou" szSaintJean: .asciz "Saint Jean Pla de Corts" szCluses: .asciz "Les Cluses" szAlbere: .asciz "L'Albère" szPerthus: .asciz "Le Perthus"   .align 4 TableCities: .quad szCluses // address name string .quad 251 // number of habitants .quad szCeret .quad 7705 .quad szMaureillas .quad 2596 .quad szBoulou .quad 5554 .quad szSaintJean .quad 2153 .quad szAlbere .quad 83 .quad szVives .quad 174 .quad szTaillet .quad 115 .quad szPerthus .quad 586 .quad szReynes .quad 1354 .equ NBELEMENTS, (. - TableCities) / city_end .skip city_end // temp area for element in shellSort // see other soluce to use stack // in programm arm assembly in this forum /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program   ldr x0,qAdrszMessSortHab bl affichageMess   ldr x0,qAdrTableCities // address table mov x1,0 // not use in routine mov x2,NBELEMENTS // number of élements mov x3,#city_habitants // sort by number habitants mov x4,#'N' // numeric bl shellSort ldr x0,qAdrTableCities // address table bl displayTable   ldr x0,qAdrszMessSortName bl affichageMess   ldr x0,qAdrTableCities // address table mov x1,0 // not use in routine mov x2,NBELEMENTS // number of élements mov x3,#city_name // sort by city name mov x4,#'A' // alphanumeric bl shellSort ldr x0,qAdrTableCities // address table bl displayTable   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 qAdrTableCities: .quad TableCities qAdrszMessSortHab: .quad szMessSortHab qAdrszMessSortName: .quad szMessSortName /***************************************************/ /* shell Sort */ /***************************************************/ /* x0 contains the address of table */ /* x1 contains the first element but not use !! */ /* this routine use first element at index zero !!! */ /* x2 contains the number of element */ /* x3 contains the offset of sort zone */ /* x4 contains type of sort zone N = numeric A = alphanumeric */ shellSort: 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 stp x8,x9,[sp,-16]! // save registers stp x10,x11,[sp,-16]! // save registers stp x12,x13,[sp,-16]! // save registers mov x8,x3 // save offset area sort mov x9,x4 // save type sort mov x7,city_end // element size sub x12,x2,1 // index last item mov x11,x12 // init gap = last item 1: // start loop 1 lsr x11,x11,1 // gap = gap / 2 cbz x11,100f // if gap = 0 -> end mov x3,x11 // init loop indice 1 2: // start loop 2 mul x1,x3,x7 // offset élement mov x2,NBELEMENTS mul x2,x7,x2 bl copyElement add x1,x1,x8 // + offset sort zone ldr x4,[x0,x1] // load first value mov x5,x3 // init loop indice 2 3: // start loop 3 cmp x5,x11 // indice < gap blt 7f // yes -> end loop 2 sub x6,x5,x11 // index = indice - gap mul x1,x6,x7 // compute offset add x10,x1,x8 // + offset sort zone ldr x2,[x0,x10] // load second value cmp x9,#'A' // sort area alapha ? beq 4f // yes cmp x4,x2 // else compare numeric values bge 7f // highter b 6f // lower 4: // compare area alphanumeric mov x10,#0 // counter 5: ldrb w13,[x4,x10] // byte string 1 ldrb w6,[x2,x10] // byte string 2 cmp w13,w6 bgt 7f blt 6f   cmp w13,#0 // end string 1 beq 7f // end comparaison add x10,x10,#1 // else add 1 in counter b 5b // and loop   6: mul x2,x5,x7 // offset élement bl copyElement // copy element x1 to element x2 sub x5,x5,x11 // indice = indice - gap b 3b // and loop 7: mov x1,NBELEMENTS mul x1,x7,x1 mul x2,x7,x5 bl copyElement add x3,x3,1 // increment indice 1 cmp x3,x12 // end ? ble 2b // no -> loop 2 b 1b // yes loop for new gap   100: // end function ldp x12,x13,[sp],16 // restaur 2 registers ldp x10,x11,[sp],16 // restaur 2 registers ldp x8,x9,[sp],16 // restaur 2 registers 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   /******************************************************************/ /* copy table element */ /******************************************************************/ /* r0 contains the address of table */ /* r1 offset origin element */ /* r2 offset destination element */ copyElement: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x3,0 add x1,x1,x0 add x2,x2,x0 1: ldrb w4,[x1,x3] strb w4,[x2,x3] add x3,x3,1 cmp x3,city_end blt 1b 100: 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 stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x2,x0 // table address mov x3,0 mov x6,city_end 1: // loop display table mul x4,x3,x6 add x4,x4,city_name ldr x1,[x2,x4] ldr x0,qAdrsMessResult bl strInsertAtCharInc // put name in message mov x5,x0 // save address of new message mul x4,x3,x6 add x4,x4,city_habitants // and load value ldr x0,[x2,x4] ldr x1,qAdrsZoneConv // display value bl conversion10 // call function mov x0,x5 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 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 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#ACL2
ACL2
(defun insert-by-key (o os key) (cond ((endp os) (list o)) ((< (cdr (assoc key o)) (cdr (assoc key (first os)))) (cons o os)) (t (cons (first os) (insert-by-key o (rest os) key)))))   (defun isort-by-key (os key) (if (endp os) nil (insert-by-key (first os) (isort-by-key (rest os) key) key)))   (isort-by-key '(((name . "map") (weight . 9) (value . 150)) ((name . "compass") (weight . 13) (value . 35)) ((name . "water") (weight . 153) (value . 200)) ((name . "sandwich") (weight . 50) (value . 60)) ((name . "glucose") (weight . 15) (value . 60))) 'value)
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#PicoLisp
PicoLisp
(de countingSort (Lst Min Max) (let Count (need (- Max Min -1) 0) (for N Lst (inc (nth Count (- N Min -1))) ) (make (map '((C I) (do (car C) (link (car I))) ) Count (range Min Max) ) ) ) )
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#PL.2FI
PL/I
count_sort: procedure (A); declare A(*) fixed; declare (min, max) fixed; declare i fixed binary;   max, min = A(lbound(A,1)); do i = 1 to hbound(A,1); if max < A(i) then max = A(i); if min > A(i) then min = A(i); end;   begin; declare t(min:max) fixed; declare (i, j, k) fixed binary (31); t = 0; do i = 1 to hbound(A,1); j = A(i); t(j) = t(j) + 1; end; k = lbound(A,1); do i = min to max; if t(i) ^= 0 then do j = 1 to t(i); A(k) = i; k = k + 1; end; end; end; end count_sort;
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#C.23
C#
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable;   public class Solver { private static readonly (int dx, int dy)[] //other puzzle types elided numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};   private (int dx, int dy)[] moves;   public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }));   Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); }   public Solver(params (int dx, int dy)[] moves) => this.moves = moves;   public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); }   public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); }   private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; }   private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false;   bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); }   private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); }   private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); }   private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; }   private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); }   }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Arturo
Arturo
arr: [2 3 5 8 4 1 6 9 7] sort 'arr ; in-place   loop arr => print
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#AutoHotkey
AutoHotkey
numbers = 5 4 1 2 3 sort, numbers, N D%A_Space% Msgbox % numbers
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct oid_tag { char* str_; int* numbers_; int length_; } oid;   // free memory, no-op if p is null void oid_destroy(oid* p) { if (p != 0) { free(p->str_); free(p->numbers_); free(p); } }   int char_count(const char* str, char ch) { int count = 0; for (const char* p = str; *p; ++p) { if (*p == ch) ++count; } return count; }   // construct an OID from a string // returns 0 on memory allocation failure or parse error oid* oid_create(const char* str) { oid* ptr = calloc(1, sizeof(oid)); if (ptr == 0) return 0; ptr->str_ = strdup(str); if (ptr->str_ == 0) { oid_destroy(ptr); return 0; } int dots = char_count(str, '.'); ptr->numbers_ = malloc(sizeof(int) * (dots + 1)); if (ptr->numbers_ == 0) { oid_destroy(ptr); return 0; } ptr->length_ = dots + 1; const char* p = str; for (int i = 0; i <= dots && *p;) { char* eptr = 0; int num = strtol(p, &eptr, 10); if (*eptr != 0 && *eptr != '.') { // TODO: check for overflow/underflow oid_destroy(ptr); return 0; } ptr->numbers_[i++] = num; p = eptr; if (*p) ++p; } return ptr; }   // compare two OIDs int oid_compare(const void* p1, const void* p2) { const oid* o1 = *(oid* const*)p1; const oid* o2 = *(oid* const*)p2; int i1 = 0, i2 = 0; for (; i1 < o1->length_ && i2 < o2->length_; ++i1, ++i2) { if (o1->numbers_[i1] < o2->numbers_[i2]) return -1; if (o1->numbers_[i1] > o2->numbers_[i2]) return 1; } if (o1->length_ < o2->length_) return -1; if (o1->length_ > o2->length_) return 1; return 0; }   int main() { const char* input[] = { "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0" }; const int len = sizeof(input)/sizeof(input[0]); oid* oids[len]; memset(oids, 0, sizeof(oids)); int i; for (i = 0; i < len; ++i) { oids[i] = oid_create(input[i]); if (oids[i] == 0) { fprintf(stderr, "Out of memory\n"); goto cleanup; } } qsort(oids, len, sizeof(oid*), oid_compare); for (i = 0; i < len; ++i) puts(oids[i]->str_); cleanup: for (i = 0; i < len; ++i) oid_destroy(oids[i]); return 0; }
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#Common_Lisp
Common Lisp
(defun disjoint-sort (values indices) "Destructively perform a disjoin sublist sort on VALUES with INDICES." (loop :for element :in (sort (loop :for index :across indices :collect (svref values index)) '<) :for index :across (sort indices '<) :do (setf (svref values index) element)) values)
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Liberty_BASIC
Liberty BASIC
  randomize 0.5 N=15 dim a(N,2)   for i = 0 to N-1 a(i,1)= int(i/5) a(i,2)= int(rnd(1)*5) next   print "Unsorted by column #2" print "by construction sorted by column #1" for i = 0 to N-1 print a(i,1), a(i,2) next   sort a(), 0, N-1, 2 print   print "After sorting by column #2" print "Notice wrong order by column #1" for i = 0 to N-1 print a(i,1), a(i,2), if i=0 then print else if a(i,2) = a(i-1,2) AND a(i,1) < a(i-1,1) then print "bad order" else print end if next  
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Ruby
Ruby
n = 13 p (1..n).sort_by(&:to_s)  
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Rust
Rust
fn lex_sorted_vector(num: i32) -> Vec<i32> { let (min, max) = if num >= 1 { (1, num) } else { (num, 1) }; let mut str: Vec<String> = (min..=max).map(|i| i.to_string()).collect(); str.sort(); str.iter().map(|s| s.parse::<i32>().unwrap()).collect() }   fn main() { for n in &[0, 5, 13, 21, -22] { println!("{}: {:?}", n, lex_sorted_vector(*n)); } }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Scala
Scala
object LexicographicalNumbers extends App { def ints = List(0, 5, 13, 21, -22)   def lexOrder(n: Int): Seq[Int] = (if (n < 1) n to 1 else 1 to n).sortBy(_.toString)   println("In lexicographical order:\n") for (n <- ints) println(f"$n%3d: ${lexOrder(n).mkString("[",", ", "]")}%s")   }
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Julia
Julia
# v0.6   a, b, c = "lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")" a, b, c = sort([a, b, c]) @show a b c   a, b, c = 77444, -12, 0 a, b, c = sort([a, b, c]) @show a b c
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Kotlin
Kotlin
// version 1.1.2   inline fun <reified T : Comparable<T>> sortThree(x: T, y: T, z: T): Triple<T, T, T> { val a = arrayOf(x, y, z) a.sort() return Triple(a[0], a[1], a[2]) }   fun <T> printThree(x: T, y: T, z: T) = println("x = $x\ny = $y\nz = $z\n")   fun main(args: Array<String>) { var x = "lions, tigers, and" var y = "bears, oh my!" var z = """(from the "Wizard of OZ")""" val t = sortThree(x, y, z) x = t.first y = t.second z = t.third printThree(x, y, z)   var x2 = 77444 var y2 = -12 var z2 = 0 val t2 = sortThree(x2, y2, z2) x2 = t2.first y2 = t2.second z2 = t2.third printThree(x2, y2, z2)   var x3 = 174.5 var y3 = -62.5 var z3 = 41.7 val t3 = sortThree(x3, y3, z3) x3 = t3.first y3 = t3.second z3 = t3.third printThree(x3, y3, z3) }
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Frink
Frink
f = {|a,b| len = length[b] <=> length[a] if len != 0 return len else return lexicalCompare[a,b] }   words = split[%r/\s+/, "Here are some sample strings to be sorted"] println[sort[words, f]]
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Raku
Raku
sub comb_sort ( @a is copy ) { my $gap = +@a; my $swaps = 1; while $gap > 1 or $swaps { $gap = ( ($gap * 4) div 5 ) || 1 if $gap > 1;   $swaps = 0; for ^(+@a - $gap) -> $i { my $j = $i + $gap; if @a[$i] > @a[$j] { @a[$i, $j] .= reverse; $swaps = 1; } } } return @a; }   my @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) }; say @weights.sort.Str eq @weights.&comb_sort.Str ?? 'ok' !! 'not ok';  
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#PHP
PHP
function bogosort($l) { while (!in_order($l)) shuffle($l); return $l; }   function in_order($l) { for ($i = 1; $i < count($l); $i++) if ($l[$i] < $l[$i-1]) return FALSE; return TRUE; }
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#D
D
import std.stdio, std.algorithm : swap;   T[] bubbleSort(T)(T[] data) pure nothrow { foreach_reverse (n; 0 .. data.length) { bool swapped; foreach (i; 0 .. n) if (data[i] > data[i + 1]) { swap(data[i], data[i + 1]); swapped = true; } if (!swapped) break; } return data; }     void main() { auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; writeln(array.bubbleSort()); }
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Julia
Julia
function gnomesort!(arr::Vector) i, j = 1, 2 while i < length(arr) if arr[i] ≤ arr[i+1] i = j j += 1 else arr[i], arr[i+1] = arr[i+1], arr[i] i -= 1 if i == 0 i = j j += 1 end end end return arr end   v = rand(-10:10, 10) println("# unordered: $v\n -> ordered: ", gnomesort!(v))
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#PicoLisp
PicoLisp
(de beadSort (Lst) (let Abacus (cons NIL) (for N Lst # Thread beads on poles (for (L Abacus (ge0 (dec 'N)) (cdr L)) (or (cdr L) (queue 'L (cons))) (push (cadr L) T) ) ) (make (while (gt0 (cnt pop (cdr Abacus))) # Drop and count beads (link @) ) ) ) )
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#PL.2FI
PL/I
  /* Handles both negative and positive values. */   maxval: procedure (z) returns (fixed binary); declare z(*) fixed binary; declare (maxv initial (0), i) fixed binary; do i = lbound(z,1) to hbound(z,1); maxv = max(z(i), maxv); end; put skip data (maxv); put skip; return (maxv); end maxval; minval: procedure (z) returns (fixed binary); declare z(*) fixed binary; declare (minv initial (0), i) fixed binary;   do i = lbound(z,1) to hbound(z,1); if z(i) < 0 then minv = min(z(i), minv); end; put skip data (minv); put skip; return (minv); end minval;   /* To deal with negative values, array elements are incremented */ /* by the greatest (in magnitude) negative value, thus making */ /* them positive. The resultant values are stored in an */ /* unsigned array (PL/I provides both signed and unsigned data */ /* types). At procedure end, the array values are restored to */ /* original values. */   (subrg, fofl, size, stringrange, stringsize): beadsort: procedure (z); /* 8-1-2010 */ declare (z(*)) fixed binary; declare b(maxval(z)-minval(z)+1) bit (maxval(z)-minval(z)+1) aligned; declare (i, j, k, m, n) fixed binary; declare a(hbound(z,1)) fixed binary unsigned; declare offset fixed binary initial (minval(z));   PUT SKIP LIST('CHECKPOINT A'); PUT SKIP; n = hbound(z,1); m = hbound(b,1);   if offset < 0 then a = z - offset; else a = z;   b = '0'b;   do i = 1 to n; substr(b(i), 1, a(i)) = copy('1'b, a(i)); end; do j = 1 to m; put skip list (b(j)); end;   do j = 1 to m; k = 0; do i =1 to n; if substr(b(i), j, 1) then k = k + 1; end; do i = 1 to n; substr(b(i), j, 1) = (i <= k); end; end; put skip; do j = 1 to m; put skip list (b(j)); end;   do i = 1 to n; k = 0; do j = 1 to m; k = k + substr(b(i), j, 1); end; a(i) = k; end; if offset < 0 then z = a + offset; else z = a;   end beadsort;
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#IS-BASIC
IS-BASIC
100 PROGRAM "CocktSrt.bas" 110 RANDOMIZE 120 NUMERIC ARRAY(5 TO 24) 130 CALL INIT(ARRAY) 140 CALL WRITE(ARRAY) 150 CALL COCKTAILSORT(ARRAY) 160 CALL WRITE(ARRAY) 170 DEF INIT(REF A) 180 FOR I=LBOUND(A) TO UBOUND(A) 190 LET A(I)=RND(98)+1 200 NEXT 210 END DEF 220 DEF WRITE(REF A) 230 FOR I=LBOUND(A) TO UBOUND(A) 240 PRINT A(I); 250 NEXT 260 PRINT 270 END DEF 280 DEF COCKTAILSORT(REF A) 290 LET ST=LBOUND(A)+1:LET EN=UBOUND(A):LET D,CH=1 300 DO 310 FOR J=ST TO EN STEP D 320 IF A(J-1)>A(J) THEN LET T=A(J-1):LET A(J-1)=A(J):LET A(J)=T:LET CH=J 330 NEXT 340 LET EN=ST:LET ST=CH-D:LET D=-1*D 350 LOOP UNTIL EN*D<ST*D 360 END DEF
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . Extra credits are available for other interesting designs. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Numbrix puzzle Solve the no connection puzzle
#11l
11l
V neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] V cnt = 0 V pWid = 0 V pHei = 0   F is_valid(a, b) R -1 < a & a < :pWid & -1 < b & b < :pHei   F iterate(&pa, x, y, v) I v > :cnt R 1   L(i) 0 .< :neighbours.len V a = x + :neighbours[i][0] V b = y + :neighbours[i][1] I is_valid(a, b) & pa[a][b] == 0 pa[a][b] = v V r = iterate(&pa, a, b, v + 1) I r == 1 R r pa[a][b] = 0 R 0   F solve(pz, w, h) V pa = [[-1] * h] * w V f = 0  :pWid = w  :pHei = h L(j) 0 .< h L(i) 0 .< w I pz[f] == ‘1’ pa[i][j] = 0  :cnt++ f++   L(y) 0 .< h L(x) 0 .< w I pa[x][y] == 0 pa[x][y] = 1 I 1 == iterate(&pa, x, y, 2) R (1, pa) pa[x][y] = 0 R (0, pa)   V r = solve(‘011011011111111111111011111000111000001000’, 7, 6) I r[0] == 1 L(j) 6 L(i) 7 I r[1][i][j] == -1 print(‘ ’, end' ‘’) E print(‘ #02’.format(r[1][i][j]), end' ‘’) print() E print(‘No solution!’, end' ‘’)