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/Insertion_sort
Sorting algorithms/Insertion 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 Insertion 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) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC InsertionSort(INT ARRAY a INT size) INT i,j,value   FOR i=1 TO size-1 DO value=a(i) j=i-1 WHILE j>=0 AND a(j)>value DO a(j+1)=a(j) j==-1 OD a(j+1)=value OD RETURN   PROC Test(INT ARRAY a INT size) PrintE("Array before sort:") PrintArray(a,size) InsertionSort(a,size) PrintE("Array after sort:") PrintArray(a,size) PutE() RETURN   PROC Main() INT ARRAY a(10)=[1 4 65535 0 3 7 4 8 20 65530], b(21)=[10 9 8 7 6 5 4 3 2 1 0 65535 65534 65533 65532 65531 65530 65529 65528 65527 65526], c(8)=[101 102 103 104 105 106 107 108], d(12)=[1 65535 1 65535 1 65535 1 65535 1 65535 1 65535]   Test(a,10) Test(b,21) Test(c,8) Test(d,12) RETURN
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#Maple
Maple
arr := Array([17,0,-1,72,0]): len := numelems(arr): P := Iterator:-Permute(len): for p in P do lst:= convert(arr[sort(convert(p,list),output=permutation)],list): if (ListTools:-Sorted(lst)) then print(lst): break: end if: end do:
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
PermutationSort[x_List] := NestWhile[RandomSample, x, Not[OrderedQ[#]] &]
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Before: 6 7 8 9 2 5 3 4 1 After: 9 8 7 6 2 5 3 4 1 Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). Related tasks   Number reversal game   Topswops Also see   Wikipedia article:   pancake sorting.
#Eiffel
Eiffel
  class PANCAKE_SORT [G -> COMPARABLE]   feature {NONE}   arraymax (array: ARRAY [G]; upper: INTEGER): INTEGER --- Max item of 'array' between index 1 and 'upper'. require upper_index_positive: upper >= 0 array_not_void: array /= Void local i: INTEGER cur_max: G do from i := 1 cur_max := array.item (i) Result := i until i + 1 > upper loop if array.item (i + 1) > cur_max then cur_max := array.item (i + 1) Result := i + 1 end i := i + 1 end ensure Index_positive: Result > 0 end   reverse_array (ar: ARRAY [G]; upper: INTEGER): ARRAY [G] -- Array reversed from index one to upper. require upper_positive: upper > 0 ar_not_void: ar /= Void local i, j: INTEGER new_array: ARRAY [G] do create Result.make_empty Result.deep_copy (ar) from i := 1 j := upper until i > j loop Result [i] := ar [j] Result [j] := ar [i] i := i + 1 j := j - 1 end ensure same_length: ar.count = Result.count end   sort (ar: ARRAY [G]): ARRAY [G] -- Sorted array in ascending order. local i: INTEGER do create Result.make_empty Result.deep_copy (ar) from i := ar.count until i = 1 loop Result := reverse_array (reverse_array (Result, arraymax (Result, i)), i) i := i - 1 end ensure same_length: ar.count = Result.count Result_sorted: is_sorted (Result) end   is_sorted (ar: ARRAY [G]): BOOLEAN --- Is 'ar' sorted in ascending order? require ar_not_empty: ar.is_empty = False local i: INTEGER do Result := True from i := ar.lower until i = ar.upper loop if ar [i] > ar [i + 1] then Result := False end i := i + 1 end end   feature   pancake_sort (ar: ARRAY [G]): ARRAY [G] do Result := sort (ar) end   end  
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#Maple
Maple
swap := proc(arr, a, b) local temp := arr[a]; arr[a] := arr[b]; arr[b] := temp; end proc:   stoogesort:= proc(arr, start_index, end_index) local cur; if (arr[end_index] < arr[start_index]) then swap(arr, start_index, end_index); end if;   if end_index - start_index > 1 then cur := trunc((end_index - start_index + 1)/3); stoogesort(arr, start_index, end_index - cur); stoogesort(arr, start_index + cur, end_index); stoogesort(arr, start_index, end_index - cur); end if;   return arr; end proc:     arr := Array([4, 2, 6, 1, 3, 7, 9, 5, 8]): stoogesort(arr, 1, numelems(arr));
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
stoogeSort[lst_, I_, J_] := Module[{i = I, j = J, list = lst}, If[list[[j]] < list[[i]], list[[{i,j}]] = list[[{j,i}]];] If[(j-i) > 1, t = Round[(j-i+1)/3]; list=stoogeSort[list,i,j-t]; list=stoogeSort[list,i+t,j]; list=stoogeSort[list,i,j-t];]; list ]
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Prolog
Prolog
sleep_sort(L) :- thread_pool_create(rosetta, 1024, []) , maplist(initsort, L, LID), maplist(thread_join, LID, _LStatus), thread_pool_destroy(rosetta).   initsort(V, Id) :- thread_create_in_pool(rosetta, (sleep(V), writeln(V)), Id, []).    
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#PureBasic
PureBasic
NewMap threads()   Procedure Foo(n) Delay(n) PrintN(Str(n)) EndProcedure   If OpenConsole() For i=1 To CountProgramParameters() threads(Str(i)) = CreateThread(@Foo(), Val(ProgramParameter())) Next   ForEach threads() WaitThread(threads()) Next Print("Press ENTER to exit"): Input() EndIf
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#E
E
def selectionSort := { def cswap(c, a, b) { def t := c[a] c[a] := c[b] c[b] := t println(c) }   def indexOfMin(array, first, last) { var min := array[first] var mini := first for i in (first+1)..last { if (array[i] < min) { min := array[i] mini := i } } return mini }   /** Selection sort (in-place). */ def selectionSort(array) { def last := (array.size()-1) for i in 0..(last - 1) { cswap(array, i, indexOfMin(array, i + 1, last)) } } }
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
#Erlang
Erlang
-module(soundex). -export([soundex/1]).   soundex([]) -> []; soundex(Str) -> [Head|Tail] = string:to_upper(Str), [Head | isoundex(Tail, [], todigit(Head))].   isoundex([], Acc, _) -> case length(Acc) of N when N == 3 -> lists:reverse(Acc); N when N < 3 -> isoundex([], [$0 | Acc], ignore); N when N > 3 -> isoundex([], lists:sublist(Acc, N-2, N), ignore) end; isoundex([Head|Tail], Acc, Lastn) -> Dig = todigit(Head), case Dig of Dig when Dig /= $0, Dig /= Lastn -> isoundex(Tail, [Dig | Acc], Dig); _ -> case Head of $H -> isoundex(Tail, Acc, Lastn); $W -> isoundex(Tail, Acc, Lastn); N when N >= $A, N =< $Z -> isoundex(Tail, Acc, Dig); _ -> isoundex(Tail, Acc, Lastn) % This clause handles non alpha characters end end.   todigit(Chr) -> Digits = "01230120022455012623010202", HeadOff = Chr - $A + 1, case HeadOff of N when N > 0, N < 27 -> lists:nth(HeadOff, Digits); _ -> % Treat non alpha characters as a vowel $0 end.  
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#J
J
gaps =: [: }: 1 (1+3*])^:(> {:)^:a:~ # insert =: (I.~ {. ]) , [ , ] }.~ I.~ gapinss =: #@] {. ,@|:@(] insert//.~ #@] $ i.@[) shellSort =: [: ; gapinss &.>/@(< ,~ ]&.>@gaps)
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#Java
Java
public static void shell(int[] a) { int increment = a.length / 2; while (increment > 0) { for (int i = increment; i < a.length; i++) { int j = i; int temp = a[i]; while (j >= increment && a[j - increment] > temp) { a[j] = a[j - increment]; j = j - increment; } a[j] = temp; } if (increment == 2) { increment = 1; } else { increment *= (5.0 / 11); } } }
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change. Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements. Task Specifics Given ten males: abe, bob, col, dan, ed, fred, gav, hal, ian, jon And ten females: abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan And a complete list of ranked preferences, where the most liked is to the left: abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan Use the Gale Shapley algorithm to find a stable set of engagements Perturb this set of engagements to form an unstable set of engagements then check this new set for stability. References The Stable Marriage Problem. (Eloquent description and background information). Gale-Shapley Algorithm Demonstration. Another Gale-Shapley Algorithm Demonstration. Stable Marriage Problem - Numberphile (Video). Stable Marriage Problem (the math bit) (Video). The Stable Marriage Problem and School Choice. (Excellent exposition)
#Tcl
Tcl
package require Tcl 8.5   # Functions as aliases to standard commands interp alias {} tcl::mathfunc::pos {} ::lsearch -exact interp alias {} tcl::mathfunc::nonempty {} ::llength   # The stability check proc check engaged { global preferences set inverse [lreverse $engaged] set errmsg "%s and %s like each other better than their present partners,\  %s and %s respectively" dict for {she he} $engaged { set shelikes [dict get $preferences $she] set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]] set helikes [dict get $preferences $he] set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]] foreach guy $shelikesbetter { set guysgirl [dict get $inverse $guy] set guylikes [dict get $preferences $guy] if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} { puts [format $errmsg $she $guy $he $guysgirl] return 0 } } foreach gal $helikesbetter { set galsguy [dict get $engaged $gal] set gallikes [dict get $preferences $gal] if {pos($gallikes,$galsguy) > pos($gallikes,$he)} { puts [format $errmsg $he $gal $she $galsguy] return 0 } } } return 1 }   # The match-making algorithm proc matchmaker {} { global guys gals preferences set guysfree $guys set engaged {} array set p $preferences while {nonempty($guysfree)} { set guysfree [lassign $guysfree guy] set p($guy) [set guyslist [lassign $p($guy) gal]] if {![dict exists $engaged $gal]} { # She's free dict set engaged $gal $guy puts " $guy and $gal" continue } # The bounder proposes to an engaged lass! set fiance [dict get $engaged $gal] if {pos($p($gal), $fiance) > pos($p($gal), $guy)} { # She prefers the new guy dict set engaged $gal $guy puts " $gal dumped $fiance for $guy" set guy $fiance } if {nonempty($p($guy))} { lappend guysfree $guy } } return $engaged }   # Problem dataset; preferences unified since all names distinct set guys {abe bob col dan ed fred gav hal ian jon} set gals {abi bea cath dee eve fay gay hope ivy jan} set preferences { abe {abi eve cath ivy jan dee fay bea hope gay} bob {cath hope abi dee eve fay bea jan ivy gay} col {hope eve abi dee bea fay ivy gay cath jan} dan {ivy fay dee gay hope eve jan bea cath abi} ed {jan dee bea cath fay eve abi ivy hope gay} fred {bea abi dee gay eve ivy cath jan hope fay} gav {gay eve ivy bea cath abi dee hope jan fay} hal {abi eve hope fay ivy cath jan bea gay dee} ian {hope cath dee gay bea abi fay ivy jan eve} jon {abi fay jan gay eve bea dee cath ivy hope}   abi {bob fred jon gav ian abe dan ed col hal} bea {bob abe col fred gav dan ian ed jon hal} cath {fred bob ed gav hal col ian abe dan jon} dee {fred jon col abe ian hal gav dan bob ed} eve {jon hal fred dan abe gav col ed ian bob} fay {bob abe ed ian jon dan fred gav col hal} gay {jon gav hal fred bob abe col ed dan ian} hope {gav jon bob abe ian dan hal ed col fred} ivy {ian col hal gav fred bob abe ed jon dan} jan {ed hal gav abe bob jon col ian fred dan} }   # The demonstration code puts "Engagements:" set engaged [matchmaker]   puts "\nCouples:" set pfx "" foreach gal $gals { puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]" set pfx ",\n" } puts "\n" puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"   puts "\n\nSwapping two fiances to introduce an error" set tmp [dict get $engaged [lindex $gals 0]] dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]] dict set engaged [lindex $gals 1] $tmp foreach gal [lrange $gals 0 1] { puts " $gal is now engaged to [dict get $engaged $gal]" } puts "" puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]"
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The basic stack operations are:   push   stores a new element onto the stack top;   pop   returns the last pushed stack element, while removing it from the stack;   empty   tests if the stack contains no elements. Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):   top   (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack. Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See stack machine. Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks. Task Create a stack supporting the basic operations: push, pop, empty. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Liberty_BASIC
Liberty BASIC
  global stack$ stack$=""   randomize .51 for i = 1 to 10 if rnd(1)>0.5 then print "pop => ";pop$() else j=j+1 s$ = chr$(j + 64) print "push ";s$ call push s$ end if next   print print "Clean-up" do print "pop => ";pop$() loop while not(empty()) print "Stack is empty"   end   '------------------------------------ sub push s$ stack$=s$+"|"+stack$ 'stack end sub   function pop$() if stack$="" then pop$="*EMPTY*": exit function pop$=word$(stack$,1,"|") stack$=mid$(stack$,instr(stack$,"|")+1) end function   function empty() empty =(stack$="") end function  
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8 Related tasks   Zig-zag matrix   Identity_matrix   Ulam_spiral_(for_primes)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
AddSquareRing[x_List/;Equal@@Dimensions[x] && Length[Dimensions[x]]==2]:=Module[{new=x,size,smallest}, size=Length[x]; smallest=x[[1,1]]; Do[ new[[i]]=Prepend[new[[i]],smallest-i]; new[[i]]=Append[new[[i]],smallest-3 size+i-3] ,{i,size}]; PrependTo[new,Range[smallest-3size-3-size-1,smallest-3size-3]]; AppendTo[new,Range[smallest-size-1,smallest-size-size-2,-1]]; new ] MakeSquareSpiral[size_Integer/;size>0]:=Module[{largest,start,times}, start=size^2+If[Mod[size,2]==0,{{-4,-3},{-1,-2}},{{-1}}]; times=If[Mod[size,2]==0,size/2-1,(size-1)/2]; Nest[AddSquareRing,start,times] ]
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#J
J
  radixSortR =: 3 : 0 NB. base radixSort data 16 radixSortR y : keys =. x #.^:_1 y NB. compute keys length =. #{.keys extra =. (-length) {."0 buckets =. i.x for_pass. i.-length do. keys =. ; (buckets,pass{"1 keys) <@:}./.extra,keys end. x#.keys NB. restore the data )
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#Java
Java
public static int[] sort(int[] old) { // Loop for every bit in the integers for (int shift = Integer.SIZE - 1; shift > -1; shift--) { // The array to put the partially sorted array into int[] tmp = new int[old.length]; // The number of 0s int j = 0;   // Move the 0s to the new array, and the 1s to the old one for (int i = 0; i < old.length; i++) { // If there is a 1 in the bit we are testing, the number will be negative boolean move = old[i] << shift >= 0;   // If this is the last bit, negative numbers are actually lower if (shift == 0 ? !move : move) { tmp[j] = old[i]; j++; } else { // It's a 1, so stick it in the old array for now old[i - j] = old[i]; } }   // Copy over the 1s from the old array for (int i = j; i < tmp.length; i++) { tmp[i] = old[i - j]; }   // And now the tmp array gets switched for another round of sorting old = tmp; }   return old; }
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Arc
Arc
(def qs (seq) (if (empty seq) nil (let pivot (car seq) (join (qs (keep [< _ pivot] (cdr seq))) (list pivot) (qs (keep [>= _ pivot] (cdr seq)))))))
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 Sort an array of numbers (of any convenient size) into ascending order using   Patience sorting. Related task   Longest increasing subsequence
#Haskell
Haskell
import Control.Monad.ST import Control.Monad import Data.Array.ST import Data.List import qualified Data.Set as S   newtype Pile a = Pile [a]   instance Eq a => Eq (Pile a) where Pile (x:_) == Pile (y:_) = x == y   instance Ord a => Ord (Pile a) where Pile (x:_) `compare` Pile (y:_) = x `compare` y   patienceSort :: Ord a => [a] -> [a] patienceSort = mergePiles . sortIntoPiles where   sortIntoPiles :: Ord a => [a] -> [[a]] sortIntoPiles lst = runST $ do piles <- newSTArray (1, length lst) [] let bsearchPiles x len = aux 1 len where aux lo hi | lo > hi = return lo | otherwise = do let mid = (lo + hi) `div` 2 m <- readArray piles mid if head m < x then aux (mid+1) hi else aux lo (mid-1) f len x = do i <- bsearchPiles x len writeArray piles i . (x:) =<< readArray piles i return $ if i == len+1 then len+1 else len len <- foldM f 0 lst e <- getElems piles return $ take len e where newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e) newSTArray = newArray   mergePiles :: Ord a => [[a]] -> [a] mergePiles = unfoldr f . S.fromList . map Pile where f pq = case S.minView pq of Nothing -> Nothing Just (Pile [x], pq') -> Just (x, pq') Just (Pile (x:xs), pq') -> Just (x, S.insert (Pile xs) pq')   main :: IO () main = print $ patienceSort [4, 65, 2, -31, 0, 99, 83, 782, 1]
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 Insertion 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) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#ActionScript
ActionScript
function insertionSort(array:Array) { for(var i:int = 1; i < array.length;i++) { var value = array[i]; var j:int = i-1; while(j >= 0 && array[j] > value) { array[j+1] = array[j]; j--; } array[j+1] = value; } return array; }
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#MATLAB_.2F_Octave
MATLAB / Octave
function list = permutationSort(list)   permutations = perms(1:numel(list)); %Generate all permutations of the item indicies   %Test every permutation of the indicies of the original list for i = (1:size(permutations,1)) if issorted( list(permutations(i,:)) ) list = list(permutations(i,:)); return %Once the correct permutation of the original list is found break out of the program end end   end
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#MAXScript
MAXScript
fn inOrder arr = ( if arr.count < 2 then return true else ( local i = 1 while i < arr.count do ( if arr[i+1] < arr[i] do return false i += 1 ) return true ) )   fn permutations arr = ( if arr.count <= 1 then return arr else ( for i = 1 to arr.count do ( local rest = for r in 1 to arr.count where r != i collect arr[r] local permRest = permutations rest local new = join #(arr[i]) permRest if inOrder new do return new ) ) )
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Before: 6 7 8 9 2 5 3 4 1 After: 9 8 7 6 2 5 3 4 1 Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). Related tasks   Number reversal game   Topswops Also see   Wikipedia article:   pancake sorting.
#Elena
Elena
import extensions;   extension op { pancakeSort() { var list := self.clone();   int i := list.Length;   if (i < 2) { ^ self };   while (i > 1) { int max_num_pos := 0; int a := 0; while (a < i) { if (list[a] > list[max_num_pos]) { max_num_pos := a };   a += 1 };   if (max_num_pos == i - 1) { } else { if (max_num_pos > 0) { list.flip(list.Length, max_num_pos + 1) };   list.flip(list.Length, i) }; i -= 1 };   ^ list }   flip(int length, int num) { int i := 0; int count := num - 1; while (i < count) { var swap := self[i]; self[i] := self[count]; self[count] := swap;   i += 1; count -= 1 } } }   public program() { var list := new int[]{6, 7, 8, 9, 2, 5, 3, 4, 1};   console.printLine("before:", list.asEnumerable()); console.printLine("after :", list.pancakeSort().asEnumerable()) }
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Before: 6 7 8 9 2 5 3 4 1 After: 9 8 7 6 2 5 3 4 1 Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). Related tasks   Number reversal game   Topswops Also see   Wikipedia article:   pancake sorting.
#Elixir
Elixir
defmodule Sort do def pancake_sort(list) when is_list(list), do: pancake_sort(list, length(list))   defp pancake_sort(list, 0), do: list defp pancake_sort(list, limit) do index = search_max(list, limit) flip(list, index) |> flip(limit) |> pancake_sort(limit-1) end   defp search_max([h | t], limit), do: search_max(t, limit, 2, h, 1)   defp search_max(_, limit, index, _, max_index) when limit<index, do: max_index defp search_max([h | t], limit, index, max, max_index) do if h > max, do: search_max(t, limit, index+1, h, index), else: search_max(t, limit, index+1, max, max_index) end   defp flip(list, n), do: flip(list, n, [])   defp flip(list, 0, reverse), do: reverse ++ list defp flip([h | t], n, reverse) do flip(t, n-1, [h | reverse]) end end   IO.inspect list = Enum.shuffle(1..9) IO.inspect Sort.pancake_sort(list)
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#MATLAB_.2F_Octave
MATLAB / Octave
%Required inputs: %i = 1 %j = length(list) % function list = stoogeSort(list,i,j)   if list(j) < list(i) list([i j]) = list([j i]); end   if (j - i) > 1 t = round((j-i+1)/3); list = stoogeSort(list,i,j-t); list = stoogeSort(list,i+t,j); list = stoogeSort(list,i,j-t); end   end
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Python
Python
from time import sleep from threading import Timer   def sleepsort(values): sleepsort.result = [] def add1(x): sleepsort.result.append(x) mx = values[0] for v in values: if mx < v: mx = v Timer(v, add1, [v]).start() sleep(mx+1) return sleepsort.result   if __name__ == '__main__': x = [3,2,4,7,3,6,9,1] if sleepsort(x) == sorted(x): print('sleep sort worked for:',x) else: print('sleep sort FAILED for:',x)
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#EasyLang
EasyLang
subr sort for i = 0 to len data[] - 2 min_pos = i for j = i + 1 to len data[] - 1 if data[j] < data[min_pos] min_pos = j . . swap data[i] data[min_pos] . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] call sort print data[]
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#EchoLisp
EchoLisp
  ;; recursive version (adapted from Racket) (lib 'list) ;; list-delete (define (sel-sort xs (x0)) (cond [(null? xs) null] [else (set! x0 (apply min xs)) (cons x0 (sel-sort (list-delete xs x0)))]))   (sel-sort (shuffle (iota 13))) → (0 1 2 3 4 5 6 7 8 9 10 11 12)   ;; straightforward and more efficient implementation using list-swap! (define (sel-sort list) (maplist (lambda( L) (first (list-swap! L (first L) (apply min L )))) list))   (sel-sort (shuffle (iota 13))) → (0 1 2 3 4 5 6 7 8 9 10 11 12)    
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
#F.23
F#
module Soundex   let soundex (s : string) = let code c = match c with | 'B' | 'F' | 'P' | 'V' -> Some('1') | 'C' | 'G' | 'J' | 'K' | 'Q' | 'S' | 'X' | 'Z' -> Some('2') | 'D' | 'T' -> Some('3') | 'L' -> Some('4') | 'M' | 'N' -> Some('5') | 'R' -> Some('6') | _ -> None   let rec p l = match l with | [] -> [] | x :: y :: tail when (code x) = (code y) -> (p (y :: tail)) | x :: 'W' :: y :: tail when (code x) = (code y) -> (p (y :: tail)) | x :: 'H' :: y :: tail when (code x) = (code y) -> (p (y :: tail)) | x :: tail -> (code x) :: (p tail)   let chars = match (p (s.ToUpper() |> List.ofSeq)) with | [] -> "" | head :: tail -> new string((s.[0] :: (tail |> List.filter (fun x -> x.IsSome) |> List.map (fun x -> x.Value))) |> List.toArray) chars.PadRight(4, '0').Substring(0, 4)   let test (input, se) = printfn "%12s\t%s\t%s" input se (soundex input)   let testCases = [| ("Ashcraft", "A261"); ("Ashcroft", "A261"); ("Burroughs", "B620"); ("Burrows", "B620"); ("Ekzampul", "E251"); ("Example", "E251"); ("Ellery", "E460"); ("Euler", "E460"); ("Ghosh", "G200"); ("Gauss", "G200"); ("Gutierrez", "G362"); ("Heilbronn", "H416"); ("Hilbert", "H416"); ("Jackson", "J250"); ("Kant", "K530"); ("Knuth", "K530"); ("Lee", "L000"); ("Lukasiewicz", "L222"); ("Lissajous", "L222"); ("Ladd", "L300"); ("Lloyd", "L300"); ("Moses", "M220"); ("O'Hara", "O600"); ("Pfister", "P236"); ("Rubin", "R150"); ("Robert", "R163"); ("Rupert", "R163"); ("Soundex", "S532"); ("Sownteks", "S532"); ("Tymczak", "T522"); ("VanDeusen", "V532"); ("Washington", "W252"); ("Wheaton", "W350"); |]   [<EntryPoint>] let main args = testCases |> Array.sortBy (fun (_, x) -> x) |> Array.iter test System.Console.ReadLine() |> ignore   0  
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#JavaScript
JavaScript
function shellSort (a) { for (var h = a.length; h > 0; h = parseInt(h / 2)) { for (var i = h; i < a.length; i++) { var k = a[i]; for (var j = i; j >= h && k < a[j - h]; j -= h) a[j] = a[j - h]; a[j] = k; } } return a; }   var a = []; var n = location.href.match(/\?(\d+)|$/)[1] || 10; for (var i = 0; i < n; i++) a.push(parseInt(Math.random() * 100)); shellSort(a); document.write(a.join(" "));
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change. Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements. Task Specifics Given ten males: abe, bob, col, dan, ed, fred, gav, hal, ian, jon And ten females: abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan And a complete list of ranked preferences, where the most liked is to the left: abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan Use the Gale Shapley algorithm to find a stable set of engagements Perturb this set of engagements to form an unstable set of engagements then check this new set for stability. References The Stable Marriage Problem. (Eloquent description and background information). Gale-Shapley Algorithm Demonstration. Another Gale-Shapley Algorithm Demonstration. Stable Marriage Problem - Numberphile (Video). Stable Marriage Problem (the math bit) (Video). The Stable Marriage Problem and School Choice. (Excellent exposition)
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash main() { # Our ten males: local males=(abe bob col dan ed fred gav hal ian jon)   # And ten females: local females=(abi bea cath dee eve fay gay hope ivy jan)   # Everyone's preferences, ranked most to least desirable: local abe=( abi eve cath ivy jan dee fay bea hope gay ) local abi=( bob fred jon gav ian abe dan ed col hal ) local bea=( bob abe col fred gav dan ian ed jon hal ) local bob=(cath hope abi dee eve fay bea jan ivy gay ) local cath=(fred bob ed gav hal col ian abe dan jon ) local col=(hope eve abi dee bea fay ivy gay cath jan ) local dan=( ivy fay dee gay hope eve jan bea cath abi ) local dee=(fred jon col abe ian hal gav dan bob ed ) local ed=( jan dee bea cath fay eve abi ivy hope gay ) local eve=( jon hal fred dan abe gav col ed ian bob ) local fay=( bob abe ed ian jon dan fred gav col hal ) local fred=( bea abi dee gay eve ivy cath jan hope fay ) local gav=( gay eve ivy bea cath abi dee hope jan fay ) local gay=( jon gav hal fred bob abe col ed dan ian ) local hal=( abi eve hope fay ivy cath jan bea gay dee ) local hope=( gav jon bob abe ian dan hal ed col fred) local ian=(hope cath dee gay bea abi fay ivy jan eve ) local ivy=( ian col hal gav fred bob abe ed jon dan ) local jan=( ed hal gav abe bob jon col ian fred dan ) local jon=( abi fay jan gay eve bea dee cath ivy hope)   # A place to store the engagements: local -A engagements=()   # Our list of free males, initially comprised of all of them: local freemales=( "${males[@]}" )   # Now we use the Gale-Shapley algorithm to find a stable set of engagements   # Loop over the free males. Note that we can't use for..in because the body # of the loop may modify the array we're looping over local -i m=0 while (( m < ${#freemales[@]} )); do local male=${freemales[m]} let m+=1   # This guy's preferences eval 'local his=("${'"$male"'[@]}")'   # Starting with his favorite local -i f=0 local female=${his[f]}   # Find her preferences eval 'local hers=("${'"$female"'[@]}")'   # And her current fiancé, if any local fiance=${engagements[$female]}   # If she has a fiancé and prefers him to this guy, look for this guy's next # best choice while [[ -n $fiance ]] && (( $(index "$male" "${hers[@]}") > $(index "$fiance" "${hers[@]}") )); do let f+=1 female=${his[f]} eval 'hers=("${'"$female"'[@]}")' fiance=${engagements[$female]} done   # If we're still on someone who's engaged, it means she prefers this guy # to her current fiancé. Dump him and put him at the end of the free list. if [[ -n $fiance ]]; then freemales+=("$fiance") printf '%-4s rejected %-4s\n' "$female" "$fiance" fi   # We found a match! Record it engagements[$female]=$male printf '%-4s accepted %-4s\n' "$female" "$male" done   # Display the final result, which should be stable print_couples engagements   # Verify its stability print_stable engagements "${females[@]}"   # Try a swap printf '\nWhat if cath and ivy swap partners?\n' local temp=${engagements[cath]} engagements[cath]=${engagements[ivy]} engagements[ivy]=$temp   # Display the new result, which should be unstable print_couples engagements   # Verify its instability print_stable engagements "${females[@]}" }   # utility function - get index of an item in an array index() { local needle=$1 shift local haystack=("$@") local -i i for i in "${!haystack[@]}"; do if [[ ${haystack[i]} == $needle ]]; then printf '%d\n' "$i" return 0 fi done return 1 }   # print the couples from the engagement array; takes name of array as argument print_couples() { printf '\nCouples:\n' local keys mapfile -t keys < <(eval 'printf '\''%s\n'\'' "${!'"$1"'[@]}"' | sort) local female for female in "${keys[@]}"; do eval 'local male=${'"$1"'["'"$female"'"]}' printf '%-4s is engaged to %-4s\n' "$female" "$male" done printf '\n' }   # print whether a set of engagements is stable; takes name of engagement array # followed by the list of females print_stable() { if stable "$@"; then printf 'These couples are stable.\n' else printf 'These couples are not stable.\n' fi }   # determine if a set of engagements is stable; takes name of engagement array # followed by the list of females stable() { local dict=$1 shift eval 'local shes=("${!'"$dict"'[@]}")' eval 'local hes=("${'"$dict"'[@]}")' local -i i local -i result=0 for (( i=0; i<${#shes[@]}; ++i )); do local she=${shes[i]} he=${hes[i]} eval 'local his=("${'"$he"'[@]}")' local alt for alt in "$@"; do eval 'local fiance=${'"$dict"'["'"$alt"'"]}' eval 'local hers=("${'"$alt"'[@]}")' if (( $(index "$she" "${his[@]}") > $(index "$alt" "${his[@]}") && $(index "$fiance" "${hers[@]}") > $(index "$he" "${hers[@]}") )) then printf '%-4s is engaged to %-4s but prefers %4s, ' "$he" "$she" "$alt" printf 'while %-4s is engaged to %-4s but prefers %4s.\n' "$alt" "$fiance" "$he" result=1 fi done done if (( result )); then printf '\n'; fi return $result }   main "$@"
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The basic stack operations are:   push   stores a new element onto the stack top;   pop   returns the last pushed stack element, while removing it from the stack;   empty   tests if the stack contains no elements. Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):   top   (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack. Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See stack machine. Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks. Task Create a stack supporting the basic operations: push, pop, empty. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Lingo
Lingo
-- parent script "Stack"   property _tos   on push (me, data) me._tos = [#data:data, #next:me._tos] end   on pop (me) if voidP(me._tos) then return VOID data = me._tos.data me._tos = me._tos.next return data end   on peek (me) if voidP(me._tos) then return VOID return me._tos.data end   on empty (me) return voidP(me.peek()) end
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8 Related tasks   Zig-zag matrix   Identity_matrix   Ulam_spiral_(for_primes)
#MATLAB
MATLAB
function matrix = reverseSpiral(n)   matrix = (-spiral(n))+n^2;   if mod(n,2)==0 matrix = flipud(matrix); else matrix = fliplr(matrix); end   end %reverseSpiral
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#jq
jq
# Sort the input array; # "base" must be an integer greater than 1 def radix_sort(base): # We only need the ceiling of non-negatives: def ceil: if . == floor then . else (. + 1 | floor) end;   min as $min | map(. - $min) | ((( max|log) / (base|log)) | ceil) as $rounds | reduce range(0; $rounds) as $i # state: [ base^i, buckets ] ( [1, .]; .[0] as $base_i | reduce .[1][] as $n ([]; (($n/$base_i) % base) as $digit | .[$digit] += [$n] ) | [($base_i * base), (map(select(. != null)) | flatten)] ) | .[1] | map(. + $min) ;   def radix_sort: radix_sort(10);  
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#Julia
Julia
function radixsort(tobesorted::Vector{Int64}) arr = deepcopy(tobesorted) for shift in 63:-1:0 tmp = Vector{Int64}(undef, length(arr)) j = 0 for i in 1:length(arr) if (shift == 0) == ((arr[i] << shift) >= 0) arr[i - j] = arr[i] else tmp[j + 1] = arr[i] j += 1 end end tmp[j+1:end] .= arr[1:length(tmp)-j] arr = tmp end arr end   function testradixsort() arrays = [[170, 45, 75, -90, -802, 24, 2, 66], [-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028]] for array in arrays println(radixsort(array)) end end   testradixsort()  
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program quickSort.s */ /* look pseudo code in wikipedia quicksort */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" sMessResult: .ascii "Value  : " sMessValeur: .fill 11, 1, ' ' @ size => 11 szCarriageReturn: .asciz "\n"   .align 4 iGraine: .int 123456 .equ NBELEMENTS, 10 #TableNumber: .int 9,5,6,1,2,3,10,8,4,7 #TableNumber: .int 1,3,5,2,4,6,10,8,4,7 #TableNumber: .int 1,3,5,2,4,6,10,8,4,7 #TableNumber: .int 1,2,3,4,5,6,10,8,4,7 TableNumber: .int 10,9,8,7,6,5,4,3,2,1 #TableNumber: .int 13,12,11,10,9,8,7,6,5,4,3,2,1 /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   1: ldr r0,iAdrTableNumber @ address number table   mov r1,#0 @ indice first item mov r2,#NBELEMENTS @ number of élements bl triRapide @ call quicksort 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   iAdrsMessValeur: .int sMessValeur 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     /***************************************************/ /* Appel récursif Tri Rapide quicksort */ /***************************************************/ /* r0 contains the address of table */ /* r1 contains index of first item */ /* r2 contains the number of elements > 0 */ triRapide: push {r2-r5,lr} @ save registers sub r2,#1 @ last item index cmp r1,r2 @ first > last ? bge 100f @ yes -> end mov r4,r0 @ save r0 mov r5,r2 @ save r2 bl partition1 @ cutting into 2 parts mov r2,r0 @ index partition mov r0,r4 @ table address bl triRapide @ sort lower part add r1,r2,#1 @ index begin = index partition + 1 add r2,r5,#1 @ number of elements bl triRapide @ sort higter part   100: @ end function pop {r2-r5,lr} @ restaur registers bx lr @ return     /******************************************************************/ /* Partition table elements */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains index of first item */ /* r2 contains index of last item */   partition1: push {r1-r7,lr} @ save registers ldr r3,[r0,r2,lsl #2] @ load value last index mov r4,r1 @ init with first index mov r5,r1 @ init with first index 1: @ begin loop ldr r6,[r0,r5,lsl #2] @ load value cmp r6,r3 @ compare value ldrlt r7,[r0,r4,lsl #2] @ if < swap value table strlt r6,[r0,r4,lsl #2] strlt r7,[r0,r5,lsl #2] addlt r4,#1 @ and increment index 1 add r5,#1 @ increment index 2 cmp r5,r2 @ end ? blt 1b @ no loop ldr r7,[r0,r4,lsl #2] @ swap value str r3,[r0,r4,lsl #2] str r7,[r0,r2,lsl #2] mov r0,r4 @ return index partition 100: pop {r1-r7,lr} bx lr   /******************************************************************/ /* 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,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult 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 /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL   1: @ start loop bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ else previous position bne 1b @ and loop @ and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b @ and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value //mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3 //movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3 ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD    
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 Sort an array of numbers (of any convenient size) into ascending order using   Patience sorting. Related task   Longest increasing subsequence
#Icon
Icon
#--------------------------------------------------------------------- # # Patience sorting. #   procedure patience_sort (less, lst) local piles   piles := deal (less, lst) return k_way_merge (less, piles) end   procedure deal (less, lst) local piles local x local i   piles := [] every x := !lst do { i := find_pile (less, x, piles) if i = *piles + 1 then { # Start a new pile after the existing ones. put (piles, [x]) } else { # Push the new value onto the top of an existing pile. push (piles[i], x) } } return piles end   procedure find_pile (less, x, piles) local i, j, k   # # Do a Bottenbruch search for the leftmost pile whose top is greater # than or equal to x. Return an index such that: # # * if x is greater than the top element at the far right, then # the index returned will be num-piles. # # * otherwise, x is greater than every top element to the left of # index, and less than or equal to the top elements at index and # to the right of index. # # References: # # * H. Bottenbruch, "Structure and use of ALGOL 60", Journal of # the ACM, Volume 9, Issue 2, April 1962, pp.161-221. # https://doi.org/10.1145/321119.321120 # # The general algorithm is described on pages 214 and 215. # # * https://en.wikipedia.org/w/index.php?title=Binary_search_algorithm&oldid=1062988272#Alternative_procedure #   j := 0 k := *piles - 1 until j = k do { i := (j + k) / 2 if less (piles[j + 1][1], x) then { j := i + 1 } else { k := i } } if j = *piles - 1 & less (piles[j + 1][1], x) then { # We need a new pile. j +:= 1 } return j + 1 end   #--------------------------------------------------------------------- # # k-way merge by tournament tree. # # See Knuth, volume 3, and also # https://en.wikipedia.org/w/index.php?title=K-way_merge_algorithm&oldid=1047851465#Tournament_Tree # # However, I store a winners tree instead of the recommended losers # tree. If the tree were stored as linked nodes, it would probably be # more efficient to store a losers tree. However, I am storing the # tree as an Icon list, and one can find an opponent quickly by simply # toggling the least significant bit of a competitor's array index. #   record infinity ()   procedure is_infinity (x) return type (x) == "infinity" end   procedure k_way_merge (less, lists) local merged_list   # Return the merge as a list, which is guaranteed to be freshly # allocated.   every put (merged_list := [], generate_k_way_merge (less, lists)) return merged_list end   procedure generate_k_way_merge (less, lists)   # Generate the results of the merge.   case *lists of { 0 : fail 1 : every suspend !(lists[1]) default : every suspend generate_merged_lists (less, lists) } end   procedure generate_merged_lists (less, lists) local indices local winners local winner, winner_index local i local next_value   indices := list (*lists, 2) winners := build_tree (less, lists) until is_infinity (winners[1][1]) do { suspend winners[1][1] winner_index := winners[1][2] next_value := get_next (lists, indices, winner_index) i := ((*winners + 1) / 2) + winner_index - 1 winners[i] := [next_value, winner_index] replay_games (less, winners, i) } end   procedure build_tree (less, lists) local total_external_nodes local total_nodes local winners local i, j local istart local i1, i2 local elem1, elem2 local iwinner, winner   total_external_nodes := next_power_of_two (*lists) total_nodes := (2 * total_external_nodes) - 1 winners := list (total_nodes) every i := 1 to total_external_nodes do { j := total_external_nodes + (i - 1) if *lists < i | *(lists[i]) = 0 then { winners[j] := [infinity (), i] } else { winners[j] := [lists[i][1], i] } } istart := total_external_nodes while istart ~= 1 do { every i := istart to (2 * istart) - 1 by 2 do { i1 := i i2 := ixor (i, 1) elem1 := winners[i1][1] elem2 := winners[i2][1] iwinner := (if play_game (less, elem1, elem2) then i1 else i2) winner := winners[iwinner] winners[i / 2] := winner } istart /:= 2 } return winners end   procedure replay_games (less, winners, i) local i1, i2 local elem1, elem2 local iwinner, winner   until i = 1 do { i1 := i i2 := ixor (i1, 1) elem1 := winners[i1][1] elem2 := winners[i2][1] iwinner := (if play_game (less, elem1, elem2) then i1 else i2) winner := winners[iwinner] i /:= 2 winners[i] := winner } return end   procedure play_game (less, x, y) if is_infinity (x) then fail if is_infinity (y) then return if less (y, x) then fail return end   procedure get_next (lists, indices, i) local next_value   if *(lists[i]) < indices[i] then { next_value := infinity () } else { next_value := lists[i][indices[i]] indices[i] +:= 1 } return next_value end   procedure next_power_of_two (n) local i   # This need not be a fast implementation. Also, it need not return # any value less than 2; a single list requires no merge. i := 2 while i < n do i +:= i return i end   #---------------------------------------------------------------------   procedure main () local example_numbers   example_numbers := [22, 15, 98, 82, 22, 4, 58, 70, 80, 38, 49, 48, 46, 54, 93, 8, 54, 2, 72, 84, 86, 76, 53, 37, 90]   writes ("unsorted ") every writes (" ", !example_numbers) write () writes ("sorted ") every writes (" ", !patience_sort ("<", example_numbers)) write () end   #---------------------------------------------------------------------
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 Insertion 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) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#Ada
Ada
type Data_Array is array(Natural range <>) of Integer;   procedure Insertion_Sort(Item : in out Data_Array) is First : Natural := Item'First; Last  : Natural := Item'Last; Value : Integer; J  : Integer; begin for I in (First + 1)..Last loop Value := Item(I); J := I - 1; while J in Item'range and then Item(J) > Value loop Item(J + 1) := Item(J); J := J - 1; end loop; Item(J + 1) := Value; end loop; end Insertion_Sort;
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.util.List import java.util.ArrayList   numeric digits 20   class RSortingPermutationsort public   properties private static iterations maxIterations   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method permutationSort(vlist = List) public static returns List perm = RPermutationIterator(vlist) iterations = 0 maxIterations = RPermutationIterator.factorial(vlist.size()) loop while perm.hasNext() iterations = iterations + 1 pl = List perm.next() if isSorted(pl) then leave else pl = null end return pl   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method isSorted(ss = List) private static returns boolean status = isTrue loop ix = 1 while ix < ss.size() vleft = Rexx ss.get(ix - 1) vright = Rexx ss.get(ix) if vleft.datatype('N') & vright.datatype('N') then vtest = vleft > vright -- For numeric types we must use regular comparison. else vtest = vleft >> vright -- For non-numeric/mixed types we must do strict comparison. if vtest then do status = isFalse leave ix end end ix return status   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static placesList = - "UK London, US New York, US Boston, US Washington" - "UK Washington, US Birmingham, UK Birmingham, UK Boston" anotherList = 'Alpha, Beta, Gamma, Beta' reversed = '7, 6, 5, 4, 3, 2, 1' unsorted = '734, 3, 1, 24, 324, -1024, -666, -1, 0, 324, 99999999' lists = [makeList(placesList), makeList(anotherList), makeList(reversed), makeList(unsorted)] loop il = 0 while il < lists.length vlist = lists[il] say vlist runtime = System.nanoTime() rlist = permutationSort(vlist) runtime = System.nanoTime() - runtime if rlist \= null then say rlist else say 'sort failed' say 'This permutation sort of' vlist.size() 'elements took' iterations 'passes (of' maxIterations') to complete. \-' say 'Elapsed time:' (runtime / 10 ** 9)'s.' say end il return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method makeList(in) public static returns List lst = ArrayList() loop while in > '' parse in val ',' in lst.add(val.strip()) end return lst -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static runSample(Rexx(args)) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method isTrue() public static returns boolean return (1 == 1) -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method isFalse() public static returns boolean return (1 == 0)  
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Before: 6 7 8 9 2 5 3 4 1 After: 9 8 7 6 2 5 3 4 1 Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). Related tasks   Number reversal game   Topswops Also see   Wikipedia article:   pancake sorting.
#Euphoria
Euphoria
function flip(sequence s, integer n) object temp for i = 1 to n/2 do temp = s[i] s[i] = s[n-i+1] s[n-i+1] = temp end for return s end function   function pancake_sort(sequence s) integer m for i = length(s) to 2 by -1 do m = 1 for j = 2 to i do if compare(s[j], s[m]) > 0 then m = j end if end for   if m < i then if m > 1 then s = flip(s,m) end if s = flip(s,i) end if end for return s end function   constant s = rand(repeat(100,10))   ? s ? pancake_sort(s)
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#MAXScript
MAXScript
fn stoogeSort arr i: j: = ( if i == unsupplied do i = 1 if j == unsupplied do j = arr.count   if arr[j] < arr[i] do ( swap arr[j] arr[i] ) if j - i > 1 do ( local t = (j - i+1)/3 arr = stoogeSort arr i:i j:(j-t) arr = stoogeSort arr i:(i+t) j:j arr = stoogeSort arr i:i j:(j-t) ) return arr )
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   iList = [int 1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] sList = Arrays.copyOf(iList, iList.length)   sList = stoogeSort(sList)   lists = [iList, sList] loop ln = 0 to lists.length - 1 cl = lists[ln] rpt = Rexx('') loop ct = 0 to cl.length - 1 rpt = rpt cl[ct] end ct say '['rpt.strip().changestr(' ', ',')']' end ln   return   method stoogeSort(L_ = int[], i_ = 0, j_ = L_.length - 1) public static returns int[]   if L_[j_] < L_[i_] then do Lt = L_[i_] L_[i_] = L_[j_] L_[j_] = Lt end if j_ - i_ > 1 then do t_ = (j_ - i_ + 1) % 3 L_ = stoogeSort(L_, i_, j_ - t_) L_ = stoogeSort(L_, i_ + t_, j_) L_ = stoogeSort(L_, i_, j_ - t_) end   return L_  
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Racket
Racket
  #lang racket   ;; accepts a list to sort (define (sleep-sort lst) (define done (make-channel)) (for ([elem lst]) (thread (λ () (sleep elem) (channel-put done elem)))) (for/list ([_ (length lst)]) (channel-get done)))   ;; outputs '(2 5 5 7 8 9 10) (sleep-sort '(5 8 2 7 9 10 5))  
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Raku
Raku
await map -> $delay { start { sleep $delay ; say $delay } }, <6 8 1 12 2 14 5 2 1 0>;
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#REXX
REXX
/*REXX program implements a sleep sort (with numbers entered from the command line (CL).*/ numeric digits 300 /*over the top, but what the hey! */ /* (above) ··· from vaudeville. */ @.= /*placeholder for the array of numbers.*/ stuff= 1e9 50 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0 /*alphabetically ··· so far.*/ parse arg numbers /*obtain optional arguments from the CL*/ if numbers='' then numbers= stuff /*Not specified? Then use the default.*/ N= words(numbers) /*N is the number of numbers in list. */ w= length(N) /*width of N (used for nice output). */ parse upper version !ver . /*obtain which REXX we're running under*/ !regina= ('REXX-REGINA'==left(!ver, 11) ) /*indicate (or not) if this is Regina. */ say N 'numbers to be sorted:' numbers /*informative informational information*/ /*from department of redundancy depart.*/ do j=1 for N /*let's start to boogie─woogie da sort.*/ @.j= word(numbers, j) /*plug in a single number at a time. */ if datatype(@.j, 'N') then @.j= @.j / 1 /*normalize it if it's a numeric number*/ if !regina then call fork /*only REGINA REXX supports FORK BIF.*/ call sortItem j /*start a sort for an array number. */ end /*j*/   do forever while \inOrder(N) /*wait for the sorts to complete. */ call delay 1 /*one second is minimum effective time.*/ end /*forever while*/ /*well heck, other than zero seconds. */   m= max(length(@.1), length(@.N) ) /*width of smallest or largest number. */ say; say 'after sort:' /*display a blank line and a title. */   do k=1 for N /*list the (sorted) array's elements.*/ say left('', 20) 'array element' right(k, w) '───►' right(@.k, m) end /*k*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ sortItem: procedure expose @.; parse arg ? /*sorts a single (numeric) item. */ do Asort=1 until \switched /*sort unsorted array until it's sorted*/ switched= 0 /*it's all hunky─dorey, happy─dappy ···*/ do i=1 while @.i\=='' & \switched if @.? >= @.i then iterate /*item is in order. */ parse value @.? @.i with @.i @.? switched= 1 /* [↑] swapped one.*/ end /*i*/ if Asort//?==0 then call delay switched /*sleep if last item*/ end /*Asort*/ return /*Sleeping Beauty awakes. Not to worry: (c)=circa 1697.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ inOrder: procedure expose @.; parse arg howMany /*is the array in numerical order? */ do m=1 for howMany-1; next= m+1; if @.m>@.next then return 0 /*¬ in order*/ end /*m*/ /*keep looking for fountain of youth. */ return 1 /*yes, indicate with an indicator. */
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#Eiffel
Eiffel
  class SELECTION_SORT [G -> COMPARABLE]   feature {NONE}   index_of_min (ar: ARRAY [G]; lower: INTEGER): INTEGER --Index of smallest element in 'ar' in the range of lower and the max index. require lower_positiv: lower >= 1 lower_in_range: lower <= ar.count ar_not_void: ar /= Void local i: INTEGER min: G do from i := lower min := ar.item (i) Result := i until i + 1 > ar.count loop if ar.item (i + 1) < min then min := ar.item (i + 1) Result := i + 1 end i := i + 1 end ensure result_is_set: Result /= Void end   sort (ar: ARRAY [G]): ARRAY [G] -- sort array ar with selectionsort require ar_not_void: ar /= Void local min_index: INTEGER ith: G do create Result.make_empty Result.deep_copy (ar) across Result as ic loop min_index := index_of_min (Result, ic.cursor_index) ith := Result [ic.cursor_index] Result [ic.cursor_index] := Result [min_index] Result [min_index] := ith end ensure Result_is_set: Result /= Void Result_sorted: is_sorted (Result) = True end   is_sorted (ar: ARRAY [G]): BOOLEAN --- Is 'ar' sorted in ascending order? require ar_not_empty: ar.is_empty = False local i: INTEGER do Result := True from i := ar.lower until i = ar.upper loop if ar [i] > ar [i + 1] then Result := False end i := i + 1 end end   feature   selectionsort (ar: ARRAY [G]): ARRAY [G] do Result := sort (ar) end   end  
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
#Factor
Factor
USE: soundex "soundex" soundex  ! S532 "example" soundex  ! E251 "ciondecks" soundex  ! C532 "ekzampul" soundex  ! E251
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#jq
jq
# The "while" loops are implemented using the following jq function:   # 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;   # sort the input array def shellSort: length as $length | [ ($length/2|floor), .] # L1: state: [h, array] | do_until( .[0] == 0; .[0] as $h | reduce range($h; $length) as $i # L2: state: array ( .[1]; .[$i] as $k | [ $i, . ] # L3: state: [j, array] | do_until( .[0] < $h or ($k >= .[1][.[0] - $h]); .[0] as $j | [ ($j - $h), (.[1]|setpath([$j]; .[$j - $h])) ] ) | .[0] as $j | (.[1]|setpath([$j]; $k)) # i.e. a[j] = $k ) | [(($h+1)*5/11 | floor), .] ) | .[1] ;
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#Julia
Julia
# v0.6   function shellsort!(a::Array{Int})::Array{Int} incr = div(length(a), 2) while incr > 0 for i in incr+1:length(a) j = i tmp = a[i] while j > incr && a[j - incr] > tmp a[j] = a[j-incr] j -= incr end a[j] = tmp end if incr == 2 incr = 1 else incr = floor(Int, incr * 5.0 / 11) end end return a end   x = rand(1:10, 10) @show x shellsort!(x) @assert issorted(x)
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change. Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements. Task Specifics Given ten males: abe, bob, col, dan, ed, fred, gav, hal, ian, jon And ten females: abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan And a complete list of ranked preferences, where the most liked is to the left: abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan Use the Gale Shapley algorithm to find a stable set of engagements Perturb this set of engagements to form an unstable set of engagements then check this new set for stability. References The Stable Marriage Problem. (Eloquent description and background information). Gale-Shapley Algorithm Demonstration. Another Gale-Shapley Algorithm Demonstration. Stable Marriage Problem - Numberphile (Video). Stable Marriage Problem (the math bit) (Video). The Stable Marriage Problem and School Choice. (Excellent exposition)
#Ursala
Ursala
men =   { 'abe': <'abi','eve','cath','ivy','jan','dee','fay','bea','hope','gay'>, 'bob': <'cath','hope','abi','dee','eve','fay','bea','jan','ivy','gay'>, 'col': <'hope','eve','abi','dee','bea','fay','ivy','gay','cath','jan'>, 'dan': <'ivy','fay','dee','gay','hope','eve','jan','bea','cath','abi'>, 'ed': <'jan','dee','bea','cath','fay','eve','abi','ivy','hope','gay'>, 'fred': <'bea','abi','dee','gay','eve','ivy','cath','jan','hope','fay'>, 'gav': <'gay','eve','ivy','bea','cath','abi','dee','hope','jan','fay'>, 'hal': <'abi','eve','hope','fay','ivy','cath','jan','bea','gay','dee'>, 'ian': <'hope','cath','dee','gay','bea','abi','fay','ivy','jan','eve'>, 'jon': <'abi','fay','jan','gay','eve','bea','dee','cath','ivy','hope'>}   women =   { 'abi': <'bob','fred','jon','gav','ian','abe','dan','ed','col','hal'>, 'bea': <'bob','abe','col','fred','gav','dan','ian','ed','jon','hal'>, 'cath': <'fred','bob','ed','gav','hal','col','ian','abe','dan','jon'>, 'dee': <'fred','jon','col','abe','ian','hal','gav','dan','bob','ed'>, 'eve': <'jon','hal','fred','dan','abe','gav','col','ed','ian','bob'>, 'fay': <'bob','abe','ed','ian','jon','dan','fred','gav','col','hal'>, 'gay': <'jon','gav','hal','fred','bob','abe','col','ed','dan','ian'>, 'hope': <'gav','jon','bob','abe','ian','dan','hal','ed','col','fred'>, 'ivy': <'ian','col','hal','gav','fred','bob','abe','ed','jon','dan'>, 'jan': <'ed','hal','gav','abe','bob','jon','col','ian','fred','dan'>}   match = # finds a stable list of engagements from data as given above   -+ ^=rrmhPnXS ^/~&l ^/~&rl ^|DlrHSs/~& ^TlK2hlPrSLPAS\~&r -+ ~&lK2hlPrSXS, *=rnmihBPK12D ~&mmhPnXNCB^rnPrmPllSPcA\~&r ~&lrrPwZK17@rnPlX+-, ^|rrPlrlPXX/~& ^/~&nNAS ^/~&l+ ^|H\~&+ -:+ * ^|/~& -<+ \/-=+ ~&DSL@tK33+-   preferred = # finds non-couples that would prefer each other to their betrothed   ~&lSLPrSLrlXS2c^|DlrHS\~& ~~irlXX+ ^D/~&l+ ^|H\~&+ -:+ *T ^|/~& //~=;+ -~l;+ \/~&H   #cast %sWLm   main = # stable, perturbed, and preferred alternatives to the perturbed   < 'stable': match/men women, 'perturbed': ~&lSrSxPp match/men women, 'preferred': preferred/(men,women) ~&lSrSxPp match/men women>
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The basic stack operations are:   push   stores a new element onto the stack top;   pop   returns the last pushed stack element, while removing it from the stack;   empty   tests if the stack contains no elements. Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):   top   (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack. Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See stack machine. Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks. Task Create a stack supporting the basic operations: push, pop, empty. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Logo
Logo
make "stack [] push "stack 1 push "stack 2 push "stack 3 print pop "stack  ; 3 print empty? :stack ; false
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8 Related tasks   Zig-zag matrix   Identity_matrix   Ulam_spiral_(for_primes)
#Maxima
Maxima
spiral(n) := block([a, i, j, k, p, di, dj, vi, vj, imin, imax, jmin, jmax], a: zeromatrix(n, n), vi: [1, 0, -1, 0], vj: [0, 1, 0, -1], imin: 0, imax: n, jmin: 1, jmax: n + 1, p: 1, di: vi[p], dj: vj[p], i: 1, j: 1, for k from 1 thru n*n do ( a[j, i]: k, i: i + di, j: j + dj, if i < imin or i > imax or j < jmin or j > jmax then ( i: i - di, j: j - dj, p: mod(p, 4) + 1, di: vi[p], dj: vj[p], i: i + di, j: j + dj, if p = 1 then imax: imax - 1 elseif p = 2 then jmax: jmax - 1 elseif p = 3 then imin: imin + 1 else jmin: jmin + 1 ) ), a )$   spiral(5); /* matrix([ 1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]) */
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#Kotlin
Kotlin
// version 1.1.2   fun radixSort(original: IntArray): IntArray { var old = original // Need this to be mutable // Loop for every bit in the integers for (shift in 31 downTo 0) { val tmp = IntArray(old.size) // The array to put the partially sorted array into var j = 0 // The number of 0s // Move the 0s to the new array, and the 1s to the old one for (i in 0 until old.size) { // If there is a 1 in the bit we are testing, the number will be negative val move = (old[i] shl shift) >= 0 // If this is the last bit, negative numbers are actually lower val toBeMoved = if (shift == 0) !move else move if (toBeMoved) tmp[j++] = old[i] else { // It's a 1, so stick it in the old array for now old[i - j] = old[i] } } // Copy over the 1s from the old array for (i in j until tmp.size) tmp[i] = old[i - j] // And now the tmp array gets switched for another round of sorting old = tmp } return old }   fun main(args: Array<String>) { val arrays = arrayOf( intArrayOf(170, 45, 75, -90, -802, 24, 2, 66), intArrayOf(-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028) ) for (array in arrays) println(radixSort(array).contentToString()) }
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Arturo
Arturo
quickSort: function [items][ if 2 > size items -> return items   pivot: first items left: select slice items 1 (size items)-1 'x -> x < pivot right: select slice items 1 (size items)-1 'x -> x >= pivot   ((quickSort left) ++ pivot) ++ quickSort right ]   print quickSort [3 1 2 8 5 7 9 4 6]
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 Sort an array of numbers (of any convenient size) into ascending order using   Patience sorting. Related task   Longest increasing subsequence
#J
J
  Until =: 2 :'u^:(0=v)^:_' Filter =: (#~`)(`:6)   locate_for_append =: 1 i.~ (<&> {:S:0) NB. returns an index append =: (<@:(({::~ >:) , 0 {:: [)`]`(}.@:[)}) :: [ pile =: (, append locate_for_append)/@:(;/) NB. pile DATA   smallest =: ((>:@:i. , ]) <./)@:({:S:0@:}.) NB. index of pile with smallest value , that value transfer =: (}:&.>@:({~ {.) , <@:((0{::[),{:@:]))`(1 0 * ])`[} unpile =: >@:{.@:((0<#S:0)Filter@:(transfer smallest)Until(1=#))@:(a:&,)   patience_sort =: unpile@:pile   assert (/:~ -: patience_sort) ?@$~30 NB. test with 30 randomly chosen integers   Show =: 1 : 0 smoutput y u y : smoutput A=:x ,&:< y x u y )   pile_demo =: (, append Show locate_for_append)/@:(;/) NB. pile DATA unpile_demo =: >@:{.@:((0<#S:0)Filter@:(transfer Show smallest)Until(1=#))@:(a:&,) patience_sort_demo =: unpile_demo@:pile_demo  
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 Insertion 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) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#ALGOL_68
ALGOL 68
MODE DATA = REF CHAR;   PROC in place insertion sort = (REF[]DATA item)VOID: BEGIN INT first := LWB item; INT last := UPB item; INT j; DATA value; FOR i FROM first + 1 TO last DO value := item[i]; j := i - 1; # WHILE j >= LWB item AND j <= UPB item ANDF item[j] > value DO // example of ANDF extension # WHILE ( j >= LWB item AND j <= UPB item | item[j]>value | FALSE ) DO # no extension! # item[j + 1] := item[j]; j -:= 1 OD; item[j + 1] := value OD END # in place insertion sort #;   [32]CHAR data := "big fjords vex quick waltz nymph"; [UPB data]DATA ref data; FOR i TO UPB data DO ref data[i] := data[i] OD; in place insertion sort(ref data); FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line); print((data))
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#Nim
Nim
iterator permutations[T](ys: openarray[T]): seq[T] = var d = 1 c = newSeq[int](ys.len) xs = newSeq[T](ys.len)   for i, y in ys: xs[i] = y yield xs   block outter: while true: while d > 1: dec d c[d] = 0 while c[d] >= d: inc d if d >= ys.len: break outter   let i = if (d and 1) == 1: c[d] else: 0 swap xs[i], xs[d] yield xs inc c[d]   proc isSorted[T](s: openarray[T]): bool = var last = low(T) for c in s: if c < last: return false last = c return true   proc permSort[T](a: openarray[T]): seq[T] = for p in a.permutations: if p.isSorted: return p   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] echo a.permSort
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#OCaml
OCaml
let rec sorted = function | e1 :: e2 :: r -> e1 <= e2 && sorted (e2 :: r) | _ -> true   let rec insert e = function | [] -> [[e]] | h :: t as l -> (e :: l) :: List.map (fun t' -> h :: t') (insert e t)   let permute xs = List.fold_right (fun h z -> List.concat (List.map (insert h) z)) xs [[]]   let permutation_sort l = List.find sorted (permute l)
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Before: 6 7 8 9 2 5 3 4 1 After: 9 8 7 6 2 5 3 4 1 Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). Related tasks   Number reversal game   Topswops Also see   Wikipedia article:   pancake sorting.
#F.23
F#
open System   let show data = data |> Array.iter (printf "%d ") ; printfn "" let split (data: int[]) pos = data.[0..pos], data.[(pos+1)..]   let flip items pos = let lower, upper = split items pos Array.append (Array.rev lower) upper   let pancakeSort items = let rec loop data limit = if limit <= 0 then data else let lower, upper = split data limit let indexOfMax = lower |> Array.findIndex ((=) (Array.max lower)) let partialSort = Array.append (flip lower indexOfMax |> Array.rev) upper loop partialSort (limit-1)   loop items ((Array.length items)-1)
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#Nim
Nim
proc stoogeSort[T](a: var openarray[T], i, j: int) = if a[j] < a[i]: swap a[i], a[j] if j - i > 1: let t = (j - i + 1) div 3 stoogeSort(a, i, j - t) stoogeSort(a, i + t, j) stoogeSort(a, i, j - t)   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] stoogeSort a, 0, a.high echo a
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#Objeck
Objeck
  bundle Default { class Stooge { function : Main(args : String[]) ~ Nil { nums := [1, 4, 5, 3, -6, 3, 7, 10, -2, -5]; StoogeSort(nums); each(i : nums) { IO.Console->Print(nums[i])->Print(","); }; IO.Console->PrintLine(); }   function : native : StoogeSort(l : Int[]) ~ Nil { StoogeSort(l, 0, l->Size() - 1); }   function : native : StoogeSort(l : Int[], i : Int, j : Int) ~ Nil { if(l[j] < l[i]) { tmp := l[i]; l[i] := l[j]; l[j] := tmp; };   if(j - i > 1) { t := (j - i + 1) / 3; StoogeSort(l, i, j - t); StoogeSort(l, i + t, j); StoogeSort(l, i, j - t); }; } } }  
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Ruby
Ruby
require 'thread'   nums = ARGV.collect(&:to_i) sorted = [] mutex = Mutex.new   threads = nums.collect do |n| Thread.new do sleep 0.01 * n mutex.synchronize {sorted << n} end end threads.each {|t| t.join}   p sorted
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Rust
Rust
use std::thread;   fn sleepsort<I: Iterator<Item=u32>>(nums: I) { let threads: Vec<_> = nums.map(|n| thread::spawn(move || { thread::sleep_ms(n); println!("{}", n); })).collect(); for t in threads { t.join(); } }   fn main() { sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap())); }
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Scala
Scala
object SleepSort {   def main(args: Array[String]): Unit = { val nums = args.map(_.toInt) sort(nums) Thread.sleep(nums.max * 21) // Keep the JVM alive for the example }   def sort(nums: Seq[Int]): Unit = nums.foreach(i => new Thread { override def run() { Thread.sleep(i * 20) // just `i` is unpredictable with small numbers print(s"$i ") } }.start())   }
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#Elena
Elena
import extensions; import system'routines;   extension op { selectionSort() { var copy := self.clone();   for(int i := 0, i < copy.Length, i += 1) { int k := i; for(int j := i + 1, j < copy.Length, j += 1) { if (copy[j] < copy[k]) { k := j } }; copy.exchange(i,k) };   ^ copy } }   public program() { var list := new string[]{"this", "is", "a", "test", "of", "generic", "selection", "sort"};   console.printLine("before:",list.asEnumerable()); console.printLine("after:",list.selectionSort().asEnumerable()) }
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#Elixir
Elixir
defmodule Sort do def selection_sort(list) when is_list(list), do: selection_sort(list, [])   defp selection_sort([], sorted), do: sorted defp selection_sort(list, sorted) do max = Enum.max(list) selection_sort(List.delete(list, max), [max | sorted]) end end
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
#Forth
Forth
: alpha-table create does> swap 32 or [char] a - 0 max 26 min + 1+ c@ ;   alpha-table soundex-code ," 123 12. 22455 12623 1.2 2 " \ ABCDEFGHIJKLMNOPQRSTUVWXYZ   : soundex ( name len -- pad len ) over c@ pad c! \ First character verbatim pad 1+ 3 [char] 0 fill \ Pad to four characters with zeros 1 pad c@ soundex-code ( count code ) 2swap bounds do i c@ soundex-code ( count code next ) 2dup = if drop else \ runs are ignored dup [char] . = if drop else \ W, H don't separate runs of consonants dup bl = if nip else \ vowels separate consonants but aren't coded nip 2dup swap pad + c! swap 1+ tuck 4 = if leave then then then then loop 2drop pad 4 ;   \ Knuth's test cases s" Euler" soundex cr type \ E460 s" Gauss" soundex cr type \ G200 s" Hilbert" soundex cr type \ H416 s" Knuth" soundex cr type \ K530 s" Lloyd" soundex cr type \ L300 s" Lukasiewicz" soundex cr type \ L222 (W test) s" Ellery" soundex cr type \ E460 s" Ghosh" soundex cr type \ G200 s" Heilbronn" soundex cr type \ H416 s" Kant" soundex cr type \ K530 s" Ladd" soundex cr type \ L300 s" Lissajous" soundex cr type \ L222   s" Wheaton" soundex cr type \ W350 s" Ashcraft" soundex cr type \ A261 (H tests) s" Burroughs" soundex cr type \ B620 s" Burrows" soundex cr type \ B620 (W test) (any Welsh names?) s" O'Hara" soundex cr type \ O600 (punctuation test)
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#Kotlin
Kotlin
// version 1.1.0   val gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1) // Marcin Ciura's gap sequence   fun shellSort(a: IntArray) { for (gap in gaps) { for (i in gap until a.size) { val temp = a[i] var j = i while (j >= gap && a[j - gap] > temp) { a[j] = a[j - gap] j -= gap } a[j] = temp } } }   fun main(args: Array<String>) { val aa = arrayOf( intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199), intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1), intArrayOf(62, 83, 18, 53, 7, 17, 95, 86, 47, 69, 25, 28) ) for (a in aa) { shellSort(a) println(a.joinToString(", ")) } }
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change. Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements. Task Specifics Given ten males: abe, bob, col, dan, ed, fred, gav, hal, ian, jon And ten females: abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan And a complete list of ranked preferences, where the most liked is to the left: abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan Use the Gale Shapley algorithm to find a stable set of engagements Perturb this set of engagements to form an unstable set of engagements then check this new set for stability. References The Stable Marriage Problem. (Eloquent description and background information). Gale-Shapley Algorithm Demonstration. Another Gale-Shapley Algorithm Demonstration. Stable Marriage Problem - Numberphile (Video). Stable Marriage Problem (the math bit) (Video). The Stable Marriage Problem and School Choice. (Excellent exposition)
#VBA
VBA
2 methods will be shown here: 1 - using basic VBA-features for strings 2 - using the scripting.dictionary library
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The basic stack operations are:   push   stores a new element onto the stack top;   pop   returns the last pushed stack element, while removing it from the stack;   empty   tests if the stack contains no elements. Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):   top   (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack. Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See stack machine. Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks. Task Create a stack supporting the basic operations: push, pop, empty. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Logtalk
Logtalk
  :- object(stack).   :- public(push/3). push(Element, Stack, [Element| Stack]).   :- public(pop/3). pop([Top| Stack], Top, Stack).   :- public(empty/1) empty([]).   :- end_object.  
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8 Related tasks   Zig-zag matrix   Identity_matrix   Ulam_spiral_(for_primes)
#MiniZinc
MiniZinc
  %Spiral Matrix. Nigel Galloway, February 3rd., 2020 int: Size; array [1..Size,1..Size] of var 1..Size*Size: spiral; constraint spiral[1,1..]=1..Size; constraint forall(n in 2..(Size+1) div 2)(forall(g in n..Size+1-n)(spiral[n,g]=spiral[n,g-1]+1)); constraint forall(n in 1..(Size+1) div 2)(forall(g in n+1..Size+1-n)(spiral[g,Size-n+1]=spiral[g-1,Size-n+1]+1)); constraint forall(n in 1..Size div 2)(forall(g in n..Size-n)(spiral[Size-n+1,g]=spiral[Size-n+1,g+1]+1)) /\ forall(n in 1..Size div 2)(forall(g in n+1..Size-n)(spiral[g,n]=spiral[g+1,n]+1)); output [show2d(spiral)];  
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[SortByPos, RadixSort] SortByPos[data : {_List ..}, pos_Integer] := Module[{digs, order}, digs = data[[All, pos]]; order = Ordering[digs]; data[[order]] ] RadixSort[x : {_Integer ..}] := Module[{y, digs, maxlen, offset}, offset = Min[x]; y = x - offset; digs = IntegerDigits /@ y; maxlen = Max[Length /@ digs]; digs = IntegerDigits[#, 10, maxlen] & /@ y; digs = Fold[SortByPos, digs, -Range[maxlen]]; digs = FromDigits /@ digs; digs += offset; digs ]
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#Nim
Nim
func radixSort[T](a: openArray[T]): seq[T] =   result = @a   ## Loop for every bit in the integers. for shift in countdown(63, 0): var tmp = newSeq[T](result.len) # The array to put the partially sorted array into. var j = 0 # The number of 0s. for i in 0..result.high: # If there is a 1 in the bit we are testing, the number will be negative. let move = result[i] shl shift >= 0 # If this is the last bit, negative numbers are actually lower. let toBeMoved = if shift == 0: not move else: move if toBeMoved: tmp[j] = result[i] inc j else: # It's a 1, so stick it in the result array for now. result[i - j] = result[i] # Copy over the 1s from the old array. for i in j..tmp.high: tmp[i] = result[i - j] # And now the tmp array gets switched for another round of sorting. result.shallowCopy(tmp)     when isMainModule:   const arrays = [@[170, 45, 75, -90, -802, 24, 2, 66], @[-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028]]   for a in arrays: echo radixSort(a)
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#ATS
ATS
(*------------------------------------------------------------------*) (* Quicksort in ATS2, for non-linear lists. *) (*------------------------------------------------------------------*)   #include "share/atspre_staload.hats"   #define NIL list_nil () #define :: list_cons   (*------------------------------------------------------------------*)   (* A simple quicksort working on "garbage-collected" linked lists, with first element as pivot. This is meant as a demonstration, not as a superior sort algorithm.   It is based on the "not-in-place" task pseudocode. *)   datatype comparison_result = | first_is_less_than_second of () | first_is_equal_to_second of () | first_is_greater_than_second of ()   extern fun {a : t@ype} list_quicksort$comparison (x : a, y : a) :<> comparison_result   extern fun {a : t@ype} list_quicksort {n  : int} (lst : list (a, n)) :<> list (a, n)   (* - - - - - - - - - - - - - - - - - - - - - - *)   implement {a} list_quicksort {n} (lst) = let fun partition {n  : nat} .<n>. (* Proof of termination. *) (lst  : list (a, n), pivot : a)  :<> [n1, n2, n3 : int | n1 + n2 + n3 == n] @(list (a, n1), list (a, n2), list (a, n3)) = (* This implementation is *not* tail recursive. I may get a scolding for using ATS to risk stack overflow! However, I need more practice writing non-tail routines. :) Also, a lot of programmers in other languages would do it this way--especially if the lists are evaluated lazily. *) case+ lst of | NIL => @(NIL, NIL, NIL) | head :: tail => let val @(lt, eq, gt) = partition (tail, pivot) prval () = lemma_list_param lt prval () = lemma_list_param eq prval () = lemma_list_param gt in case+ list_quicksort$comparison<a> (head, pivot) of | first_is_less_than_second () => @(head :: lt, eq, gt) | first_is_equal_to_second () => @(lt, head :: eq, gt) | first_is_greater_than_second () => @(lt, eq, head :: gt) end   fun quicksort {n  : nat} .<n>. (* Proof of termination. *) (lst : list (a, n))  :<> list (a, n) = case+ lst of | NIL => lst | _ :: NIL => lst | head :: tail => let (* We are careful here to run "partition" on "tail" rather than "lst", so the termination metric will be provably decreasing. (Really the compiler *forces* us to take such care, or else to change :<> to :<!ntm>) *) val pivot = head prval () = lemma_list_param tail val @(lt, eq, gt) = partition {n - 1} (tail, pivot) prval () = lemma_list_param lt prval () = lemma_list_param eq prval () = lemma_list_param gt val eq = pivot :: eq and lt = quicksort lt and gt = quicksort gt in lt + (eq + gt) end   prval () = lemma_list_param lst in quicksort {n} lst end   (*------------------------------------------------------------------*)   val example_strings = $list ("choose", "any", "element", "of", "the", "array", "to", "be", "the", "pivot", "divide", "all", "other", "elements", "except", "the", "pivot", "into", "two", "partitions", "all", "elements", "less", "than", "the", "pivot", "must", "be", "in", "the", "first", "partition", "all", "elements", "greater", "than", "the", "pivot", "must", "be", "in", "the", "second", "partition", "use", "recursion", "to", "sort", "both", "partitions", "join", "the", "first", "sorted", "partition", "the", "pivot", "and", "the", "second", "sorted", "partition")   implement list_quicksort$comparison<string> (x, y) = let val i = strcmp (x, y) in if i < 0 then first_is_less_than_second else if i = 0 then first_is_equal_to_second else first_is_greater_than_second end   implement main0 () = let val sorted_strings = list_quicksort<string> example_strings   fun print_strings {n  : nat} .<n>. (strings : list (string, n), i  : int) : void = case+ strings of | NIL => if i <> 1 then println! () else () | head :: tail => begin print! head; if i = 8 then begin println! (); print_strings (tail, 1) end else begin print! " "; print_strings (tail, succ i) end end in println! (length example_strings); println! (length sorted_strings); print_strings (sorted_strings, 1) end   (*------------------------------------------------------------------*)
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 Sort an array of numbers (of any convenient size) into ascending order using   Patience sorting. Related task   Longest increasing subsequence
#Java
Java
import java.util.*;   public class PatienceSort { public static <E extends Comparable<? super E>> void sort (E[] n) { List<Pile<E>> piles = new ArrayList<Pile<E>>(); // sort into piles for (E x : n) { Pile<E> newPile = new Pile<E>(); newPile.push(x); int i = Collections.binarySearch(piles, newPile); if (i < 0) i = ~i; if (i != piles.size()) piles.get(i).push(x); else piles.add(newPile); }   // priority queue allows us to retrieve least pile efficiently PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles); for (int c = 0; c < n.length; c++) { Pile<E> smallPile = heap.poll(); n[c] = smallPile.pop(); if (!smallPile.isEmpty()) heap.offer(smallPile); } assert(heap.isEmpty()); }   private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> { public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); } }   public static void main(String[] args) { Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1}; sort(a); System.out.println(Arrays.toString(a)); } }
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 Insertion 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) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#ALGOL_W
ALGOL W
% insertion sorts in-place the array A. As Algol W procedures can't find the bounds % % of an array parameter, the lower and upper bounds must be specified in lb and ub  % procedure insertionSortI ( integer array A ( * ); integer value lb, ub ) ; for i := lb + 1 until ub do begin integer v, j; v := A( i ); j := i - 1; while j >= lb and A( j ) > v do begin A( j + 1 ) := A( j ); j := j - 1 end while_j_ge_0_and_Aj_gt_v ; A( j + 1 ) := v end insertionSortI ;
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#PARI.2FGP
PARI/GP
permutationSort(v)={ my(u); for(k=1,(#v)!, u=vecextract(v, numtoperm(#v,k)); for(i=2,#u, if(u[i]<u[i-1], next(2)) ); return(u) ) };
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#Perl
Perl
sub psort { my ($x, $d) = @_;   unless ($d //= $#$x) { $x->[$_] < $x->[$_ - 1] and return for 1 .. $#$x; return 1 }   for (0 .. $d) { unshift @$x, splice @$x, $d, 1; next if $x->[$d] < $x->[$d - 1]; return 1 if psort($x, $d - 1); } }   my @a = map+(int rand 100), 0 .. 10; print "Before:\t@a\n"; psort(\@a); print "After:\t@a\n"
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Before: 6 7 8 9 2 5 3 4 1 After: 9 8 7 6 2 5 3 4 1 Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). Related tasks   Number reversal game   Topswops Also see   Wikipedia article:   pancake sorting.
#Fortran
Fortran
program Pancake_Demo implicit none   integer :: list(8) = (/ 1, 4, 7, 2, 5, 8, 3, 6 /)   call Pancake_sort(list)   contains   subroutine Pancake_sort(a)   integer, intent(in out) :: a(:) integer :: i, maxpos   write(*,*) a do i = size(a), 2, -1   ! Find position of max number between index 1 and i maxpos = maxloc(a(1:i), 1)   ! is it in the correct position already? if (maxpos == i) cycle   ! is it at the beginning of the array? If not flip array section so it is if (maxpos /= 1) then a(1:maxpos) = a(maxpos:1:-1) write(*,*) a end if   ! Flip array section to get max number to correct position a(1:i) = a(i:1:-1) write(*,*) a end do   end subroutine   end program Pancake_Demo
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#OCaml
OCaml
let swap ar i j = let tmp = ar.(i) in ar.(i) <- ar.(j); ar.(j) <- tmp   let stoogesort ar = let rec aux i j = if ar.(j) < ar.(i) then swap ar i j else if j - i > 1 then begin let t = (j - i + 1) / 3 in aux (i) (j-t); aux (i+t) (j); aux (i) (j-t); end in aux 0 (Array.length ar - 1)
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Sidef
Sidef
ARGV.map{.to_i}.map{ |i| {Sys.sleep(i); say i}.fork; }.each{.wait};
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Simula
Simula
SIMULATION BEGIN   PROCESS CLASS SORTITEM(N); INTEGER N; BEGIN HOLD(N); OUTINT(N, 3); END;   INTEGER I; FOR I := 3, 2, 4, 7, 3, 6, 9, 1 DO BEGIN REF(SORTITEM) SI; SI :- NEW SORTITEM(I); ACTIVATE SI; END; HOLD(100000); OUTIMAGE;   END;
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#SNUSP
SNUSP
  /$>\ input until eof #/?<\?,/ foreach: fork \ &/:+ copy and\ /:\?-; delay / \.# print and exit thread  
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#Erlang
Erlang
  -module(solution). -import(lists,[delete/2,max/1]). -compile(export_all). selection_sort([],Sort)-> Sort; selection_sort(Ar,Sort)-> M=max(Ar), Ad=delete(M,Ar), selection_sort(Ad,[M|Sort]). print_array([])->ok; print_array([H|T])-> io:format("~p~n",[H]), print_array(T).   main()-> Ans=selection_sort([1,5,7,8,4,10],[]), print_array(Ans).  
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
#FreeBASIC
FreeBASIC
  Function getCode(c As String) As String If Instr("BFPV", c) Then Return "1" If Instr("CGJKQSXZ", c) Then Return "2" If Instr("DT", c) Then Return "3" If "L" = c Then Return "4" If Instr("MN", c) Then Return "5" If "R" = c Then Return "6" If Instr("HW", c) Then Return "." End Function   Function Soundex(palabra As String) As String palabra = Ucase(palabra) Dim As String code = Mid(palabra,1,1) Dim As String previo = getCode(Left(palabra, 1)) ''"" Dim As String actual   For i As Byte = 2 To (Len(palabra) + 1) actual = getCode(Mid(palabra, i, 1)) If actual = "." Then Continue For If Len(actual) > 0 And actual <> previo Then code &= actual previo = actual If Len(code) = 4 Then Exit For Next i If Len(code) < 4 Then code &= String(4,"0") Return Left(code,4) End Function   Dim As String nombre For i As Byte = 1 To 20 Read nombre Print """"; nombre; """"; Tab(15); Soundex(nombre) Next i   Data "Aschraft", "Ashcroft", "Euler", "Gauss", "Ghosh", "Hilbert", "Heilbronn", "Lee", "Lissajous", "Lloyd" Data "Moses", "Pfister", "Robert", "Rupert", "Rubin", "Tymczak", "VanDeusen", "Wheaton", "Soundex", "Example" Sleep  
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#Liberty_BASIC
Liberty BASIC
  siz = 100 dim a(siz) for i = 1 to siz a(i) = int(rnd(1) * 1000) next   ' ------------------------------- ' Shell Sort ' ------------------------------- incr = int(siz / 2) WHILE incr > 0 for i = 1 to siz j = i temp = a(i) WHILE (j >= incr+1 and a(abs(j-incr)) > temp) a(j) = a(j-incr) j = j - incr wend a(j) = temp next IF incr = 2 THEN incr = 1 ELSE incr = int(incr * (5 / 11)) end if WEND   for i = 1 to siz print a(i) next  
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change. Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements. Task Specifics Given ten males: abe, bob, col, dan, ed, fred, gav, hal, ian, jon And ten females: abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan And a complete list of ranked preferences, where the most liked is to the left: abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan Use the Gale Shapley algorithm to find a stable set of engagements Perturb this set of engagements to form an unstable set of engagements then check this new set for stability. References The Stable Marriage Problem. (Eloquent description and background information). Gale-Shapley Algorithm Demonstration. Another Gale-Shapley Algorithm Demonstration. Stable Marriage Problem - Numberphile (Video). Stable Marriage Problem (the math bit) (Video). The Stable Marriage Problem and School Choice. (Excellent exposition)
#Wren
Wren
import "/dynamic" for Struct   var mPref = { "abe": [ "abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"], "bob": [ "cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"], "col": [ "hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"], "dan": [ "ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"], "ed": [ "jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"], "fred": [ "bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"], "gav": [ "gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"], "hal": [ "abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"], "ian": [ "hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"], "jon": [ "abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"] }   var wPref = { "abi": { "bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5, "abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10}, "bea": { "bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5, "dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10}, "cath": { "fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5, "col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10}, "dee": { "fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5, "hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10}, "eve": { "jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5, "gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10}, "fay": { "bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5, "dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10}, "gay": { "jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5, "abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10}, "hope": { "gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5, "dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10}, "ivy": { "ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5, "bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10}, "jan": { "ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5, "jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10} }   // Pair implements the Gale/Shapely algorithm. var pair = Fn.new { |pPref, rPref| // code is destructive on the maps, so work with copies var pFree = {} for (me in pPref) pFree[me.key] = me.value var rFree = {} for (me in rPref) rFree[me.key] = me.value // struct only used in this function. // preferences must be saved in case engagement is broken. var Save = Struct.create("Save", ["proposer", "pPref", "rPref"]) var proposals = {} // key is recipient (w)   // WP pseudocode comments prefaced with WP: m is proposer, w is recipient. // WP: while ∃ free man m who still has a woman w to propose to while (pFree.count > 0) { // while there is a free proposer, var proposer var ppref for (me in pFree) { proposer = me.key ppref = me.value break // pick a proposer at random, whatever map iteration delivers first. } if (ppref.count == 0) continue // if proposer has no possible recipients, skip // WP: w = m's highest ranked such woman to whom he has not yet proposed var recipient = ppref[0] // highest ranged is first in list. ppref = ppref[1..-1] // pop from list var rpref = {} // WP: if w is free if (rpref = rFree[recipient]) { // WP: (m, w) become engaged // (common code follows if statement) } else { // WP: else some pair (m', w) already exists var s = proposals[recipient] // get proposal saved preferences // WP: if w prefers m to m' if (s.rPref[proposer] < s.rPref[s.proposer]) { System.print("engagement broken: %(recipient) %(s.proposer)") // WP: m' becomes free pFree[s.proposer] = s.pPref // return proposer to the map // WP: (m, w) become engaged rpref = s.rPref // (common code follows if statement) } else { // WP: else (m', w) remain engaged pFree[proposer] = ppref // update preferences in map continue } } System.print("engagement: %(recipient) %(proposer)") proposals[recipient] = Save.new(proposer, ppref, rpref) pFree.remove(proposer) rFree.remove(recipient) } // construct return value var ps = {} for (me in proposals) { ps[me.key] = me.value.proposer } return ps }   var validateStable = Fn.new { |ps, pPref, rPref| for (me in ps) System.print("%(me.key) %(me.value)") for (me in ps) { var r = me.key var p = me.value for (rp in pPref[p]) { if (rp == r) break var rprefs = rPref[rp] if (rprefs[p] < rprefs[ps[rp]]) { System.print("unstable.") System.print("%(p) and %(rp) would prefer each other over their current pairings.") return false } } } System.print("stable.") return true }   // get parings by Gale/Shapley algorithm var ps = pair.call(mPref, wPref) // show results System.print("\nresult:") if (!validateStable.call(ps, mPref, wPref)) return // perturb while (true) { var i = 0 var w2 = List.filled(2, null) var m2 = List.filled(2, null) for (me in ps) { w2[i] = me.key m2[i] = me.value if (i == 1) break i = i + 1 } System.print("\nexchanging partners of %(m2[0]) and %(m2[1])") ps[w2[0]] = m2[1] ps[w2[1]] = m2[0] // validate perturbed parings if (!validateStable.call(ps, mPref, wPref)) return // if those happened to be stable as well, perturb more }
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The basic stack operations are:   push   stores a new element onto the stack top;   pop   returns the last pushed stack element, while removing it from the stack;   empty   tests if the stack contains no elements. Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):   top   (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack. Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See stack machine. Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks. Task Create a stack supporting the basic operations: push, pop, empty. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#LOLCODE
LOLCODE
HAI 2.3 HOW IZ I Init YR Stak Stak HAS A Length ITZ 0 IF U SAY SO   HOW IZ I Push YR Stak AN YR Value Stak HAS A SRS Stak'Z Length ITZ Value Stak'Z Length R SUM OF Stak'Z Length AN 1 IF U SAY SO   HOW IZ I Top YR Stak FOUND YR Stak'Z SRS DIFF OF Stak'Z Length AN 1 IF U SAY SO   HOW IZ I Pop YR Stak I HAS A Top ITZ I IZ Top YR Stak MKAY Stak'Z Length R DIFF OF Stak'Z Length AN 1 FOUND YR Top IF U SAY SO   HOW IZ I Empty YR Stak FOUND YR BOTH SAEM 0 AN Stak'Z Length IF U SAY SO   I HAS A Stak ITZ A BUKKIT I IZ Init YR Stak MKAY I IZ Push YR Stak AN YR "Fred" MKAY I IZ Push YR Stak AN YR "Wilma" MKAY I IZ Push YR Stak AN YR "Betty" MKAY I IZ Push YR Stak AN YR "Barney" MKAY   IM IN YR LOOP UPPIN YR Dummy TIL I IZ Empty YR Stak MKAY VISIBLE I IZ Pop YR Stak MKAY IM OUTTA YR LOOP   KTHXBYE
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8 Related tasks   Zig-zag matrix   Identity_matrix   Ulam_spiral_(for_primes)
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   parse arg size .   if \size.datatype('W') then do printArray(generateArray(3)) say printArray(generateArray(4)) say printArray(generateArray(5)) say end else do printArray(generateArray(size)) say end   return   -- ----------------------------------------------------------------------------- method generateArray(dimension = int) private static returns int[,]   -- the output array array = int[dimension, dimension]   -- get the number of squares, including the center one if -- the dimension is odd   squares = dimension % 2 + dimension // 2   -- length of a side for the current square sidelength = dimension current = 0   loop i_ = 0 to squares - 1   -- do each side of the current square -- top side loop j_ = 0 to sidelength - 1 array[i_, i_ + j_] = current current = current + 1 end j_   -- down the right side loop j_ = 1 to sidelength - 1 array[i_ + j_, dimension - 1 - i_] = current current = current + 1 end j_   -- across the bottom loop j_ = sidelength - 2 to 0 by -1 array[dimension - 1 - i_, i_ + j_] = current current = current + 1 end j_   -- and up the left side loop j_ = sidelength - 2 to 1 by -1 array[i_ + j_, i_] = current current = current + 1 end j_   -- reduce the length of the side by two rows sidelength = sidelength - 2 end i_   return array   -- ----------------------------------------------------------------------------- method printArray(array = int[,]) private static   dimension = array[1].length rl = formatSize(array) loop i_ = 0 to dimension - 1 line = Rexx("|") loop j_ = 0 to dimension - 1 line = line Rexx(array[i_, j_]).right(rl) end j_ line = line "|" say line end i_   return   -- ----------------------------------------------------------------------------- method formatSize(array = int[,]) private static returns Rexx   dim = array[1].length maxNum = Rexx(dim * dim - 1).length()   return maxNum    
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 integer array with the   radix sort algorithm. The primary purpose is to complete the characterization of sort algorithms task.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method radixSort(tlist = Rexx[]) public static returns Rexx[]   -- scale the array to start at zero to allow handling of -ve values parse getLimits(tlist) maxn minn maxl . tlist = rescale(tlist, minn)   loop px = maxl to 1 by -1 bukits = '' loop ix = 0 to tlist.length - 1 cval = tlist[ix].right(maxl, 0) parse cval . =(px) digit +1 . bukits[digit] = bukits[digit] (cval + 0) -- simulates a stack end ix intermediates = '' loop bi = 0 to 9 intermediates = intermediates bukits[bi] -- sumulates unstack end bi -- reload array loop iw = 1 to intermediates.words() tlist[iw - 1] = intermediates.word(iw) end iw end px   -- restore the array to original scale tlist = rescale(tlist, -minn) return tlist   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method rescale(arry = Rexx[], newbase) private static returns Rexx[] loop ix = 0 to arry.length - 1 arry[ix] = arry[ix] - newbase end ix return arry -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getLimits(arry = Rexx[]) private static returns Rexx maxn = 0 minn = 0 maxl = 0 loop i_ = 0 to arry.length - 1 maxn = maxn.max(arry[i_]) minn = minn.min(arry[i_]) end i_ maxl = (maxn - minn).length() return maxn minn maxl -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static lists = [- [2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666], - [170, 45, 75, 90, 2, 24, 802, 66], - [10, 9, 8, 7, 8, 5, 4, 3, 2, 1, 0], - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - [-10, -9, -8, -7, -8, -5, -4, -3, -2, -1, -0], - [-0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10], - [-10, -19, -18, -17, -18, -15, -14, -13, -12, -11, -100], - [10, 9, 8, 7, 8, 5, 4, 3, 2, 1, 0, -0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10], - [-10, -9, -8, -7, -8, -5, -4, -3, -2, -1, -0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - ]   loop il = 0 to lists.length - 1 tlist = lists[il] say ' Input:' Arrays.asList(tlist) say 'Output:' Arrays.asList(radixSort(tlist)) say end il return  
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 Quicksort. 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 Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak 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. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#AutoHotkey
AutoHotkey
a := [4, 65, 2, -31, 0, 99, 83, 782, 7] for k, v in QuickSort(a) Out .= "," v MsgBox, % SubStr(Out, 2) return   QuickSort(a) { if (a.MaxIndex() <= 1) return a Less := [], Same := [], More := [] Pivot := a[1] for k, v in a { if (v < Pivot) less.Insert(v) else if (v > Pivot) more.Insert(v) else same.Insert(v) } Less := QuickSort(Less) Out := QuickSort(More) if (Same.MaxIndex()) Out.Insert(1, Same*) ; insert all values of same at index 1 if (Less.MaxIndex()) Out.Insert(1, Less*) ; insert all values of less at index 1 return Out }
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 Sort an array of numbers (of any convenient size) into ascending order using   Patience sorting. Related task   Longest increasing subsequence
#JavaScript
JavaScript
const patienceSort = (nums) => { const piles = []   for (let i = 0; i < nums.length; i++) { const num = nums[i] const destinationPileIndex = piles.findIndex( (pile) => num >= pile[pile.length - 1] ) if (destinationPileIndex === -1) { piles.push([num]) } else { piles[destinationPileIndex].push(num) } }   for (let i = 0; i < nums.length; i++) { let destinationPileIndex = 0 for (let p = 1; p < piles.length; p++) { const pile = piles[p] if (pile[0] < piles[destinationPileIndex][0]) { destinationPileIndex = p } } const distPile = piles[destinationPileIndex] nums[i] = distPile.shift() if (distPile.length === 0) { piles.splice(destinationPileIndex, 1) } }   return nums } console.log(patienceSort([10,6,-30,9,18,1,-20]));  
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 Insertion 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) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#AppleScript
AppleScript
-- In-place insertion sort on insertionSort(theList, l, r) -- Sort items l thru r of theList. set listLength to (count theList) if (listLength < 2) then return -- 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}   -- The list as a script property to allow faster references to its items. script o property lst : theList end script   -- Set up a minor optimisation whereby the latest instance of the highest value so far isn't -- put back into the list until either it's superseded or the end of the sort is reached. set highestSoFar to o's lst's item l set rv to o's lst's item (l + 1) if (highestSoFar > rv) then set o's lst's item l to rv else set highestSoFar to rv end if -- Work through the rest of the range, rotating values back into the sorted group as necessary. repeat with j from (l + 2) to r set rv to o's lst's item j if (highestSoFar > rv) then repeat with i from (j - 2) to l by -1 set lv to o's lst's item i if (lv > rv) then set o's lst's item (i + 1) to lv else set i to i + 1 exit repeat end if end repeat set o's lst's item i to rv else set o's lst's item (j - 1) to highestSoFar set highestSoFar to rv end if end repeat set o's lst's item r to highestSoFar   return -- nothing. end insertionSort property sort : insertionSort   -- Demo: local aList set aList to {60, 73, 11, 66, 6, 77, 41, 97, 59, 45, 64, 15, 91, 100, 22, 89, 77, 59, 54, 61} sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. return aList
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#Phix
Phix
with javascript_semantics function inOrder(sequence s) for i=2 to length(s) do if s[i]<s[i-1] then return false end if end for return true end function function permutationSort(sequence s) for n=1 to factorial(length(s)) do sequence perm = permute(n,s) if inOrder(perm) then return perm end if end for ?9/0 -- should never happen end function ?permutationSort({"dog",0,15.545,{"cat","pile","abcde",1},"cat"})
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 Implement a permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. Pseudocode: while not InOrder(list) do nextPermutation(list) done
#PHP
PHP
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; }   function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $res = permute($newitems, $newperms); if($res){ return $res; } } } }   $arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); $arr = permute($arr); echo implode(',',$arr);
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 The   merge sort   is a recursive sort of order   n*log(n). It is notable for having a worst case and average complexity of   O(n*log(n)),   and a best case complexity of   O(n)   (for pre-sorted input). The basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements   (which are both entirely sorted groups). Then merge the groups back together so that their elements are in order. This is how the algorithm gets its   divide and conquer   description. Task Write a function to sort a collection of integers using the merge sort. The merge sort algorithm comes in two parts: a sort function and a merge function The functions in pseudocode look like this: function mergesort(m) var list left, right, result if length(m) ≤ 1 return m else var middle = length(m) / 2 for each x in m up to middle - 1 add x to left for each x in m at and after middle add x to right left = mergesort(left) right = mergesort(right) if last(left) ≤ first(right) append right to left return left result = merge(left, right) return result function merge(left,right) var list result while length(left) > 0 and length(right) > 0 if first(left) ≤ first(right) append first(left) to result left = rest(left) else append first(right) to result right = rest(right) if length(left) > 0 append rest(left) to result if length(right) > 0 append rest(right) to result return result See also   the Wikipedia entry:   merge sort Note:   better performance can be expected if, rather than recursing until   length(m) ≤ 1,   an insertion sort is used for   length(m)   smaller than some threshold larger than   1.   However, this complicates the example code, so it is not shown here.
#11l
11l
F merge(left, right) [Int] result V left_idx = 0 V right_idx = 0 L left_idx < left.len & right_idx < right.len I left[left_idx] <= right[right_idx] result.append(left[left_idx]) left_idx++ E result.append(right[right_idx]) right_idx++   I left_idx < left.len result.extend(left[left_idx ..]) I right_idx < right.len result.extend(right[right_idx ..]) R result   F merge_sort(m) I m.len <= 1 R m   V middle = m.len I/ 2 V left = m[0.<middle] V right = m[middle..]   left = merge_sort(left) right = merge_sort(right) R Array(merge(left, right))   V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] print(merge_sort(arr))
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Before: 6 7 8 9 2 5 3 4 1 After: 9 8 7 6 2 5 3 4 1 Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). Related tasks   Number reversal game   Topswops Also see   Wikipedia article:   pancake sorting.
#FreeBASIC
FreeBASIC
' version 11-04-2017 ' compile with: fbc -s console ' for boundry checks on array's compile with: fbc -s console -exx   ' direction = 1, (default) sort ascending ' direction <> 1 sort descending ' show = 0, (default) do not show sorting ' show <> 0, show sorting Sub pancake_sort(a() As Long,direction As Long = 1, show As Long = 0) ' array's can have subscript range from -2147483648 to +2147483647 Dim As Long i, j, n Dim As Long lb = LBound(a) Dim As Long ub = UBound(a)   If show <> 0 Then ' show initial state For j = lb To ub Print Using "####"; a(j); Next Print End If   For i = ub To lb +1 Step -1   n = lb For j = lb +1 To i If direction = 1 Then If a(n) < a(j) Then n = j Else If a(n) > a(j) Then n = j End If Next   If n < i Then If n > lb Then For j = lb To lb + ((n - lb) \ 2) Swap a(j), a(lb + n - j) Next   If show <> 0 Then For j = lb To ub Print Using "####"; a(j); Next Print End If   End If   For j = lb To lb + ((i - lb) \ 2) Swap a(j), a(lb + i - j) Next   If show <> 0 Then For j = lb To ub Print Using "####"; a(j); Next Print End If   End If Next   End Sub   ' ------=< MAIN >=------   Dim As Long i, array(-7 To 7) Dim As Long lb = LBound(array) Dim As Long ub = UBound(array)   Randomize Timer For i = lb To ub : array(i) = i : Next For i = lb To ub ' little shuffle Swap array(i), array(Int(Rnd * (ub - lb +1) + lb)) Next   Print "unsorted "; For i = lb To ub Print Using "####"; array(i); Next Print : Print   pancake_sort(array())   Print " sorted "; For i = lb To ub Print Using "####"; array(i); Next   Print : Print Dim As Long l(10 To ...) = {0, -30, 20, -10, 0, 10, -20}   pancake_sort(l(),0,1) ' sort array l, ascending and show process   Print : Print " sorted l()"; For i = LBound(l) To UBound(l) Print Using "####"; l(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/Stooge_sort
Sorting algorithms/Stooge 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 Stooge 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 Show the   Stooge Sort   for an array of integers. The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] ↔ L[j] if j - i > 1 then t := (j - i + 1)/3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L
#ooRexx
ooRexx
/* Rexx */   call demo return exit   -- ----------------------------------------------------------------------------- -- Stooge sort implementation -- ----------------------------------------------------------------------------- ::routine stoogeSort use arg rL_, i_ = 0, j_ = .nil if j_ = .nil then j_ = rL_~items() - 1   if rL_~get(j_) < rL_~get(i_) then do Lt = rL_~get(i_) rL_~set(i_, rL_~get(j_)) rL_~set(j_, Lt) end if j_ - i_ > 1 then do t_ = (j_ - i_ + 1) % 3 rL_ = stoogeSort(rL_, i_, j_ - t_) rL_ = stoogeSort(rL_, i_ + t_, j_) rL_ = stoogeSort(rL_, i_, j_ - t_) end   return rL_   -- ----------------------------------------------------------------------------- -- Demonstrate the implementation -- ----------------------------------------------------------------------------- ::routine demo   iList = .nlist~of(1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7) sList = iList~copy()   placesList = .nlist~of( - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - )   sList = stoogeSort(sList) sortedList = stoogeSort(placesList~copy())   iLists = .list~of(iList, sList) loop ln = 0 to iLists~items() - 1 icl = iLists[ln] rpt = '' loop ct = 0 to icl~items() - 1 rpt = rpt icl[ct] end ct say '['rpt~strip()~changestr(' ', ',')']' end ln   say sLists = .list~of(placesList, sortedList) loop ln = 0 to sLists~items() - 1 scl = sLists[ln] loop ct = 0 to scl~items() - 1 say right(ct + 1, 3)':' scl[ct] end ct say end ln   return   -- ----------------------------------------------------------------------------- -- Helper class. Map get and set methods for easier conversion from java.util.List -- ----------------------------------------------------------------------------- ::class NList mixinclass List public   -- Map get() to at() ::method get use arg ix return self~at(ix)   -- Map set() to put() ::method set use arg ix, item self~put(item, ix) return  
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Swift
Swift
import Foundation   for i in [5, 2, 4, 6, 1, 7, 20, 14] { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(i * Int(NSEC_PER_SEC)))   dispatch_after(time, dispatch_get_main_queue()) { print(i) } }   CFRunLoopRun()
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
#Tcl
Tcl
#!/bin/env tclsh set count 0 proc process val { puts $val incr ::count } # Schedule the output of the values foreach val $argv { after [expr {$val * 10}] [list process $val] } # Run event loop until all values output... while {$count < $argc} { vwait count }