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/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.
#Ada
Ada
generic type Element_Type is private; type Index_Type is (<>); type Collection_Type is array(Index_Type range <>) of Element_Type; with function "<"(Left, Right : Element_Type) return Boolean is <>;   package Mergesort is function Sort(Item : Collection_Type) return Collection_Type; end MergeSort;
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.
#JavaScript
JavaScript
Array.prototype.pancake_sort = function () { for (var i = this.length - 1; i >= 1; i--) { // find the index of the largest element not yet sorted var max_idx = 0; var max = this[0]; for (var j = 1; j <= i; j++) { if (this[j] > max) { max = this[j]; max_idx = j; } }   if (max_idx == i) continue; // element already in place   var new_slice;   // flip this max element to index 0 if (max_idx > 0) { new_slice = this.slice(0, max_idx+1).reverse(); for (var j = 0; j <= max_idx; j++) this[j] = new_slice[j]; }   // then flip the max element to its place new_slice = this.slice(0, i+1).reverse(); for (var j = 0; j <= i; j++) this[j] = new_slice[j]; } return this; } ary = [7,6,5,9,8,4,3,1,2,0] sorted = ary.concat().pancake_sort();
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
#PHP
PHP
  function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }  
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].
#GAP
GAP
SelectionSort := function(v) local i, j, k, n, m; n := Size(v); for i in [1 .. n] do k := i; m := v[i]; for j in [i + 1 .. n] do if v[j] < m then k := j; m := v[j]; fi; od; v[k] := v[i]; v[i] := m; od; end;   v := List([1 .. 100], n -> Random([1 .. 100])); SelectionSort(v); v;
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].
#Go
Go
package main   import "fmt"   var a = []int{170, 45, 75, -90, -802, 24, 2, 66}   func main() { fmt.Println("before:", a) selectionSort(a) fmt.Println("after: ", a) }   func selectionSort(a []int) { last := len(a) - 1 for i := 0; i < last; i++ { aMin := a[i] iMin := i for j := i + 1; j < len(a); j++ { if a[j] < aMin { aMin = a[j] iMin = j } } a[i], a[iMin] = aMin, a[i] } }
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.
#J
J
removeDups =: {.;.1~ (1 , }. ~: }: ) codes =: ;: 'BFPV CGJKQSXZ DT L MN R HW'   soundex =: 3 : 0 if. 0=# k=.toupper y do. '0' return. end. ({.k), ,": ,. 3 {. 0-.~ }. removeDups 7 0:`(I.@:=)`]} , k >:@I.@:(e. &>)"0 _ codes )
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.
#ooRexx
ooRexx
/* Rexx */ -- --- Main -------------------------------------------------------------------- call demo return exit   -- ----------------------------------------------------------------------------- -- Shell sort implementation -- ----------------------------------------------------------------------------- ::routine shellSort use arg ra   n = ra~items() inc = format(n / 2.0,, 0) -- rounding loop label inc while inc > 0 loop i_ = inc to n - 1 temp = ra~get(i_) j_ = i_ loop label j_ while j_ >= inc if \(ra~get(j_ - inc) > temp) then leave j_ ra~set(j_, ra~get(j_ - inc)) j_ = j_ - inc end j_ ra~set(j_, temp) end i_ inc = format(inc / 2.2,, 0) -- rounding end inc   return ra   -- ----------------------------------------------------------------------------- -- Demonstrate the implementation -- ----------------------------------------------------------------------------- ::routine demo   placesList = .nlist~of( - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - )   lists = .array~of( - placesList - , shellSort(placesList~copy()) - )   loop ln = 1 to lists~items() cl = lists[ln] loop ct = 0 to cl~items() - 1 say right(ct + 1, 4)':' cl[ct] end ct say end ln return   -- ----------------------------------------------------------------------------- ::routine isTrue return 1 == 1   -- ----------------------------------------------------------------------------- ::routine isFalse return \isTrue()   -- ----------------------------------------------------------------------------- -- 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/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
#Mercury
Mercury
:- module sstack.   :- interface.   % We're going to call the type sstack (simple stack) because we don't want to get it % accidentally confused with the official stack module in the standard library. :- type sstack(T).   :- func sstack.new = sstack(T). :- pred sstack.is_empty(sstack(T)::in) is semidet. :- func sstack.push(sstack(T), T) = sstack(T). :- pred sstack.pop(T::out, sstack(T)::in, sstack(T)::out) is semidet.   :- implementation.   :- import_module list.   :- type sstack(T) ---> sstack(list(T)).   sstack.new = sstack([]).   sstack.is_empty(sstack([])).   sstack.push(Stack0, Elem) = Stack1 :- Stack0 = sstack(Elems), Stack1 = sstack([Elem | Elems]).   sstack.pop(Elem, !Stack) :-  !.Stack = sstack([Elem | Elems]),  !:Stack = sstack(Elems).   :- end_module sstack.
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)
#Pascal
Pascal
program Spiralmat; type tDir = (left,down,right,up); tdxy = record dx,dy: longint; end; tdeltaDir = array[tDir] of tdxy; const Nextdir : array[tDir] of tDir = (down,right,up,left); cDir : tDeltaDir = ((dx:1;dy:0),(dx:0;dy:1),(dx:-1;dy:0),(dx:0;dy:-1)); cMaxN = 32; type tSpiral = array[0..cMaxN,0..cMaxN] of LongInt;   function FillSpiral(n:longint):tSpiral; var b,i,k, dn,x,y : longInt; dir : tDir; tmpSp : tSpiral; BEGIN b := 0; x := 0; y := 0; //only for the first line k := -1; dn := n-1; tmpSp[x,y] := b; dir := left; repeat i := 0; while i < dn do begin inc(b); tmpSp[x,y] := b; inc(x,cDir[dir].dx); inc(y,cDir[dir].dy); inc(i); end; Dir:= NextDir[dir]; inc(k); IF k > 1 then begin k := 0; //shorten the line every second direction change dn := dn-1; if dn <= 0 then BREAK; end; until false; //the last tmpSp[x,y] := b+1; FillSpiral := tmpSp; end;   var a : tSpiral; x,y,n : LongInt; BEGIN For n := 1 to 5{cMaxN} do begin A:=FillSpiral(n); For y := 0 to n-1 do begin For x := 0 to n-1 do write(A[x,y]:4); writeln; end; writeln; end; END.  
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.
#REXX
REXX
/*REXX program performs a radix sort on an integer array (can be negative/zero/positive)*/ call gen /*call subroutine to generate numbers. */ call radSort n, w /*invoke the radix sort subroutine. */ call show /*display the elements in the @ array*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: ILF= 0 2 3 4 5 5 7. 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15 , 9 11 29 10 31 10 14 19 12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12 20 17 , 53 11 16 13 22 31 59 12 61 33 13 12 18 16 67 21 26 14 71 12 73 39 13 23 18 18 , 79 13 12 43 83 14 22 45 32 17 89 13 20 27 34 49 24 13 97 16 17 14 101 , '22 103 19 15 55 107 13 109 18 40 15 113 -42' /*excluding -42, abbreviated above list is called the integer log function*/ n= words(ILF) /* I────── L── F───────*/ w= 0; do m=1 for n; _= word(ILF,m) +0; @.m= _; w= max(w, length(_) ) end /*m*/; return /*W: is the maximum width ↑ of numbers*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ radSort: procedure expose @.; parse arg size,w; mote= c2d(' '); #= 1;  !.#._n= size !.#._b= 1; if w=='' then w= 8 !.#._i= 1; do i=1 for size; [email protected]; @.i= right(abs(y), w, 0); if y<0 then @.i= '-'@.i end /*i*/ /* [↑] negative case.*/   do while #\==0; ctr.= 0; L= 'ffff'x; low= !.#._b; n= !.#._n; $= !.#._i; H= #= #-1 /* [↑] is the radix. */ do j=low for n; parse var @.j =($) _ +1; ctr._= ctr._ + 1 if ctr._==1 & _\=='' then do; if _<<L then L=_; if _>>H then H=_ end /* ↑↑ */ end /*j*/ /* └┴─────◄─── << is a strict comparison.*/ _= /* ┌──◄─── >> " " " " */ if L>>H then iterate /*◄─────┘ */ if L==H & ctr._==0 then do; #= #+1;  !.#._b= low;  !.#._n= n;  !.#._i= $+1; iterate end L= c2d(L); H= c2d(H);  ?= ctr._ + low; top._= ?; ts= mote max= L do k=L to H; _= d2c(k, 1); c= ctr._ /* [↓] swap 2 item radices.*/ if c>ts then parse value c k with ts max;  ?= ?+c; top._= ? end /*k*/ piv= low /*set PIVot to the low part of the sort*/ do while piv<low+n it= @.piv do forever; parse var it =($) _ +1; c= top._ -1 if piv>=c then leave; top._= c;  ?= @.c; @.c= it; it= ? end /*forever*/ top._= piv; @.piv= it; piv= piv + ctr._ end /*while piv<low+n */ i= max do until i==max; _= d2c(i, 1); i= i+1; if i>H then i= L; d= ctr._ if d<=mote then do; if d<2 then iterate; b= top._ do k=b+1 for d-1; q= @.k do j=k-1 by -1 to b while q<<@.j; jp= j+1; @.jp= @.j end /*j*/ jp= j+1; @.jp= q end /*k*/ iterate end #= #+1;  !.#._b= top._;  !.#._n= d;  !.#._i= $ + 1 end /*until i==max*/ end /*while #\==0 */ #= 0 /* [↓↓↓] handle neg. and pos. arrays. */ do i=size by -1 for size; if @.i>=0 then iterate; #= #+1; @@.#= @.i end /*i*/ do j=1 for size; if @.j>=0 then do; #= #+1; @@.#= @.j; end; @.j= @@.j+0 end /*j*/ /* [↑↑↑] combine 2 lists into 1 list. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: do j=1 for n; say 'item' right(j, w) "after the radix sort:" right(@.j, w) end /*j*/; return /* [↑] display sorted items ───► term.*/
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.
#C.23
C#
// // The Tripartite conditional enables Bentley-McIlroy 3-way Partitioning. // This performs additional compares to isolate islands of keys equal to // the pivot value. Use unless key-equivalent classes are of small size. // #define Tripartite   namespace RosettaCode { using System; using System.Diagnostics;   public class QuickSort<T> where T : IComparable { #region Constants public const UInt32 INSERTION_LIMIT_DEFAULT = 12; private const Int32 SAMPLES_MAX = 19; #endregion   #region Properties public UInt32 InsertionLimit { get; } private T[] Samples { get; } private Int32 Left { get; set; } private Int32 Right { get; set; } private Int32 LeftMedian { get; set; } private Int32 RightMedian { get; set; } #endregion   #region Constructors public QuickSort(UInt32 insertionLimit = INSERTION_LIMIT_DEFAULT) { this.InsertionLimit = insertionLimit; this.Samples = new T[SAMPLES_MAX]; } #endregion   #region Sort Methods public void Sort(T[] entries) { Sort(entries, 0, entries.Length - 1); }   public void Sort(T[] entries, Int32 first, Int32 last) { var length = last + 1 - first; while (length > 1) { if (length < InsertionLimit) { InsertionSort<T>.Sort(entries, first, last); return; }   Left = first; Right = last; var median = pivot(entries); partition(median, entries); //[Note]Right < Left   var leftLength = Right + 1 - first; var rightLength = last + 1 - Left;   // // First recurse over shorter partition, then loop // on the longer partition to elide tail recursion. // if (leftLength < rightLength) { Sort(entries, first, Right); first = Left; length = rightLength; } else { Sort(entries, Left, last); last = Right; length = leftLength; } } }   /// <summary>Return an odd sample size proportional to the log of a large interval size.</summary> private static Int32 sampleSize(Int32 length, Int32 max = SAMPLES_MAX) { var logLen = (Int32)Math.Log10(length); var samples = Math.Min(2 * logLen + 1, max); return Math.Min(samples, length); }   /// <summary>Estimate the median value of entries[Left:Right]</summary> /// <remarks>A sample median is used as an estimate the true median.</remarks> private T pivot(T[] entries) { var length = Right + 1 - Left; var samples = sampleSize(length); // Sample Linearly: for (var sample = 0; sample < samples; sample++) { // Guard against Arithmetic Overflow: var index = (Int64)length * sample / samples + Left; Samples[sample] = entries[index]; }   InsertionSort<T>.Sort(Samples, 0, samples - 1); return Samples[samples / 2]; }   private void partition(T median, T[] entries) { var first = Left; var last = Right; #if Tripartite LeftMedian = first; RightMedian = last; #endif while (true) { //[Assert]There exists some index >= Left where entries[index] >= median //[Assert]There exists some index <= Right where entries[index] <= median // So, there is no need for Left or Right bound checks while (median.CompareTo(entries[Left]) > 0) Left++; while (median.CompareTo(entries[Right]) < 0) Right--;   //[Assert]entries[Right] <= median <= entries[Left] if (Right <= Left) break;   Swap(entries, Left, Right); swapOut(median, entries); Left++; Right--; //[Assert]entries[first:Left - 1] <= median <= entries[Right + 1:last] }   if (Left == Right) { Left++; Right--; } //[Assert]Right < Left swapIn(entries, first, last);   //[Assert]entries[first:Right] <= median <= entries[Left:last] //[Assert]entries[Right + 1:Left - 1] == median when non-empty } #endregion   #region Swap Methods [Conditional("Tripartite")] private void swapOut(T median, T[] entries) { if (median.CompareTo(entries[Left]) == 0) Swap(entries, LeftMedian++, Left); if (median.CompareTo(entries[Right]) == 0) Swap(entries, Right, RightMedian--); }   [Conditional("Tripartite")] private void swapIn(T[] entries, Int32 first, Int32 last) { // Restore Median entries while (first < LeftMedian) Swap(entries, first++, Right--); while (RightMedian < last) Swap(entries, Left++, last--); }   /// <summary>Swap entries at the left and right indicies.</summary> public void Swap(T[] entries, Int32 left, Int32 right) { Swap(ref entries[left], ref entries[right]); }   /// <summary>Swap two entities of type T.</summary> public static void Swap(ref T e1, ref T e2) { var e = e1; e1 = e2; e2 = e; } #endregion }   #region Insertion Sort static class InsertionSort<T> where T : IComparable { public static void Sort(T[] entries, Int32 first, Int32 last) { for (var next = first + 1; next <= last; next++) insert(entries, first, next); }   /// <summary>Bubble next entry up to its sorted location, assuming entries[first:next - 1] are already sorted.</summary> private static void insert(T[] entries, Int32 first, Int32 next) { var entry = entries[next]; while (next > first && entries[next - 1].CompareTo(entry) > 0) entries[next] = entries[--next]; entries[next] = entry; } } #endregion }
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
#OCaml
OCaml
module PatienceSortFn (Ord : Set.OrderedType) : sig val patience_sort : Ord.t list -> Ord.t list end = struct   module PilesSet = Set.Make (struct type t = Ord.t list let compare x y = Ord.compare (List.hd x) (List.hd y) end);;   let sort_into_piles list = let piles = Array.make (List.length list) [] in let bsearch_piles x len = let rec aux lo hi = if lo > hi then lo else let mid = (lo + hi) / 2 in if Ord.compare (List.hd piles.(mid)) x < 0 then aux (mid+1) hi else aux lo (mid-1) in aux 0 (len-1) in let f len x = let i = bsearch_piles x len in piles.(i) <- x :: piles.(i); if i = len then len+1 else len in let len = List.fold_left f 0 list in Array.sub piles 0 len   let merge_piles piles = let pq = Array.fold_right PilesSet.add piles PilesSet.empty in let rec f pq acc = if PilesSet.is_empty pq then acc else let elt = PilesSet.min_elt pq in match elt with [] -> failwith "Impossible" | x::xs -> let pq' = PilesSet.remove elt pq in f (if xs = [] then pq' else PilesSet.add xs pq') (x::acc) in List.rev (f pq [])   let patience_sort n = merge_piles (sort_into_piles n) 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.
#BASIC_2
BASIC
DECLARE SUB InsertionSort (theList() AS INTEGER)   DIM n(10) AS INTEGER, L AS INTEGER, o AS STRING FOR L = 0 TO 10 n(L) = INT(RND * 32768) NEXT InsertionSort n() FOR L = 1 TO 10 PRINT n(L); ";"; NEXT   SUB InsertionSort (theList() AS INTEGER) DIM insertionElementIndex AS INTEGER FOR insertionElementIndex = 1 TO UBOUND(theList) DIM insertionElement AS INTEGER insertionElement = theList(insertionElementIndex) DIM j AS INTEGER j = insertionElementIndex - 1 DO WHILE (j >= 0) 'necessary for BASICs without short-circuit evaluation IF (insertionElement < theList(j)) THEN theList(j + 1) = theList(j) j = j - 1 ELSE EXIT DO END IF LOOP theList(j + 1) = insertionElement NEXT END SUB
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
#Ring
Ring
  # Project : Sorting algorithms/Permutation sort   a = [4, 65, 2, 31, 0, 99, 2, 83, 782] result = [] permute(a,1)   for n = 1 to len(result) num = 0 for m = 1 to len(result[n]) - 1 if result[n][m] <= result[n][m+1] num = num + 1 ok next if num = len(result[n]) - 1 nr = n exit ok next see "" + nr + " permutations required to sort " + len(a) + " items." + nl   func permute(a,k) if k = len(a) add(result,a) else for i = k to len(a) temp=a[k] a[k]=a[i] a[i]=temp permute(a,k+1) temp=a[k] a[k]=a[i] a[i]=temp next ok return a  
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
#Ruby
Ruby
class Array def permutationsort permutation.each{|perm| return perm if perm.sorted?} end   def sorted? each_cons(2).all? {|a, b| a <= b} end end
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 Heapsort. 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) Heapsort is an in-place sorting algorithm with worst case and average complexity of   O(n logn). The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. A heap sort requires random access, so can only be used on an array-like data structure. Pseudocode: function heapSort(a, count) is input: an unordered array a of length count (first place a in max-heap order) heapify(a, count) end := count - 1 while end > 0 do (swap the root(maximum value) of the heap with the last element of the heap) swap(a[end], a[0]) (decrement the size of the heap so that the previous max value will stay in its proper place) end := end - 1 (put the heap back in max-heap order) siftDown(a, 0, end) function heapify(a,count) is (start is assigned the index in a of the last parent node) start := (count - 2) / 2 while start ≥ 0 do (sift down the node at index start to the proper place such that all nodes below the start index are in heap order) siftDown(a, start, count-1) start := start - 1 (after sifting down the root all nodes/elements are in heap order) function siftDown(a, start, end) is (end represents the limit of how far down the heap to sift) root := start while root * 2 + 1 ≤ end do (While the root has at least one child) child := root * 2 + 1 (root*2+1 points to the left child) (If the child has a sibling and the child's value is less than its sibling's...) if child + 1 ≤ end and a[child] < a[child + 1] then child := child + 1 (... then point to the right child instead) if a[root] < a[child] then (out of max-heap order) swap(a[root], a[child]) root := child (repeat to continue sifting down the child now) else return Write a function to sort a collection of integers using heapsort.
#AppleScript
AppleScript
-- In-place binary heap sort. -- Heap sort algorithm: J.W.J. Williams. on heapSort(theList, l, r) -- Sort items l thru r of theList. set listLen to (count theList) if (listLen < 2) then return -- Convert negative and/or transposed range indices. if (l < 0) then set l to listLen + l + 1 if (r < 0) then set r to listLen + r + 1 if (l > r) then set {l, r} to {r, l}   script o -- The list as a script property to allow faster references to its items. property lst : theList -- In a binary heap, the list index of each node's first child is (node index * 2) - (l - 1). Preset the constant part. property const : l - 1   -- Private subhandler: sift a value down into the heap from a given node. on siftDown(siftV, node, endOfHeap) set child to node * 2 - const repeat until (child comes after endOfHeap) set childV to my lst's item child if (child comes before endOfHeap) then set child2 to child + 1 set child2V to my lst's item child2 if (child2V > childV) then set child to child2 set childV to child2V end if end if if (childV > siftV) then set my lst's item node to childV set node to child set child to node * 2 - const else exit repeat end if end repeat   -- Insert the sifted-down value at the node reached. set my lst's item node to siftV end siftDown end script   -- Arrange the sort range into a "heap" with its "top" at the leftmost position. repeat with i from (l + r) div 2 to l by -1 tell o to siftDown(its lst's item i, i, r) end repeat -- Unpick the heap. repeat with endOfHeap from r to (l + 1) by -1 set endV to o's lst's item endOfHeap set o's lst's item endOfHeap to o's lst's item l tell o to siftDown(endV, l, endOfHeap - 1) end repeat   return -- nothing end heapSort property sort : heapSort   -- Demo: local aList set aList to {74, 95, 9, 56, 76, 33, 51, 27, 62, 55, 86, 60, 65, 32, 10, 62, 72, 87, 86, 85, 36, 20, 44, 17, 60} sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. return aList
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.
#ALGOL_68
ALGOL 68
MODE DATA = CHAR;   PROC merge sort = ([]DATA m)[]DATA: ( IF LWB m >= UPB m THEN m ELSE INT middle = ( UPB m + LWB m ) OVER 2; []DATA left = merge sort(m[:middle]); []DATA right = merge sort(m[middle+1:]); flex merge(left, right)[AT LWB m] FI );   # FLEX version: A demonstration of FLEX for manipulating arrays # PROC flex merge = ([]DATA in left, in right)[]DATA:( [UPB in left + UPB in right]DATA result; FLEX[0]DATA left := in left; FLEX[0]DATA right := in right;   FOR index TO UPB result DO # change the direction of this comparison to change the direction of the sort # IF LWB right > UPB right THEN result[index:] := left; stop iteration ELIF LWB left > UPB left THEN result[index:] := right; stop iteration ELIF left[1] <= right[1] THEN result[index] := left[1]; left := left[2:] ELSE result[index] := right[1]; right := right[2:] FI OD; stop iteration: result );   [32]CHAR char array data := "big fjords vex quick waltz nymph"; print((merge sort(char array data), new line));
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.
#jq
jq
def pancakeSort:   def flip(i): . as $in | ($in[0:i+1]|reverse) + $in[i+1:] ;   # If input is [] then return null def index_of_max: . as $in | reduce range(1; length) as $i # state: [ix, max] ( [ 0, $in[0] ]; if $in[$i] > .[1] then [ $i, $in[$i] ] else . end ) | .[0] ;   reduce range(0; length) as $iup (.; (length - $iup - 1) as $i | (.[0:$i+1] | index_of_max) as $max # flip about $max and then about $i unless $i == $max | if ($i == $max) then . else flip($max) | flip($i) end ) ;
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.
#Julia
Julia
function pancakesort!(arr::Vector{<:Real}) len = length(arr) if len < 2 return arr end for i in len:-1:2 j = indmax(arr[1:i]) if i == j continue end arr[1:j] = reverse(arr[1:j]) arr[1:i] = reverse(arr[1:i]) end return arr end   v = rand(-10:10, 10) println("# unordered: $v\n -> ordered: ", pancakesort!(v))
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
#PicoLisp
PicoLisp
(de stoogeSort (L N) (default N (length L)) (let P (nth L N) (when (> (car L) (car P)) (xchg L P) ) ) (when (> N 2) (let D (/ N 3) (stoogeSort L (- N D)) (stoogeSort (nth L (inc D)) (- N D)) (stoogeSort L (- N D)) ) ) L )
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
#PL.2FI
PL/I
stoogesort: procedure (L) recursive; /* 16 August 2010 */ declare L(*) fixed binary; declare (i, j, t, temp) fixed binary;   j = hbound(L,1); do i = lbound(L, 1) to j; if L(j) < L(i) then do; temp = L(i); L(i) = L(j); L(j) = temp; end; if j - i > 1 then do; t = (j - i + 1)/3; call stoogesort(L, i , j-t); call stoogesort(L, i+t, j ); call stoogesort(L, i , j-t); end; end; end stoogesort;
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].
#Haskell
Haskell
import Data.List (delete)   selSort :: (Ord a) => [a] -> [a] selSort [] = [] selSort xs = selSort (delete x xs) ++ [x] where x = maximum xs
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.
#Java
Java
public static void main(String[] args){ System.out.println(soundex("Soundex")); System.out.println(soundex("Example")); System.out.println(soundex("Sownteks")); System.out.println(soundex("Ekzampul")); }   private static String getCode(char c){ switch(c){ case 'B': case 'F': case 'P': case 'V': return "1"; case 'C': case 'G': case 'J': case 'K': case 'Q': case 'S': case 'X': case 'Z': return "2"; case 'D': case 'T': return "3"; case 'L': return "4"; case 'M': case 'N': return "5"; case 'R': return "6"; default: return ""; } }   public static String soundex(String s){ String code, previous, soundex; code = s.toUpperCase().charAt(0) + "";   // EDITED : previous = "7"; previous = getCode(s.toUpperCase().charAt(0));   for(int i = 1;i < s.length();i++){ String current = getCode(s.toUpperCase().charAt(i)); if(current.length() > 0 && !current.equals(previous)){ code = code + current; } previous = current; } soundex = (code + "0000").substring(0, 4); return soundex; }
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.
#PARI.2FGP
PARI/GP
shellSort(v)={ my(inc=#v\2); while(inc, for(i=inc+1,#v, my(t=v[i],j=i); while(j>inc && v[j-inc]>t, v[j]=v[j-=inc] ); v[j]=t ); inc \= 2.2 ); v };
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.
#Pascal
Pascal
Const MaxN = 100; { number of elements (my example is 100) } Type TArray = Array [0..MaxN] of Integer;   Procedure ShellSort ( var A : TArray; N : Integer ); Var i, j, step, tmp : Integer; Begin step:=N div 2; // step:=step shr 1 While step>0 Do Begin For i:=step to N Do Begin tmp:=A[i]; j:=i; While (j>=step) and (A[j-step]>tmp) Do Begin A[j]:=A[j-step]; dec(j,step); End; A[j]:=tmp; End; step:=step div 2; // step:=step shr 1 End; End;  
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
#MiniScript
MiniScript
// Note in Miniscript, a value of zero is false, // and any other number is true. // therefore the .len function works as the inverse of a .empty function stack = [2, 4, 6] stack.push 8 print "Stack is " + stack print "Adding '9' to stack " + stack.push(9) print "Top of stack is " + stack.pop print "Stack is " + stack if stack.len then print "Stack is not empty" else print "Stack is empty" end if
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)
#Perl
Perl
sub spiral {my ($n, $x, $y, $dx, $dy, @a) = (shift, 0, 0, 1, 0); foreach (0 .. $n**2 - 1) {$a[$y][$x] = $_; my ($nx, $ny) = ($x + $dx, $y + $dy); ($dx, $dy) = $dx == 1 && ($nx == $n || defined $a[$ny][$nx]) ? ( 0, 1) : $dy == 1 && ($ny == $n || defined $a[$ny][$nx]) ? (-1, 0) : $dx == -1 && ($nx < 0 || defined $a[$ny][$nx]) ? ( 0, -1) : $dy == -1 && ($ny < 0 || defined $a[$ny][$nx]) ? ( 1, 0) : ($dx, $dy); ($x, $y) = ($x + $dx, $y + $dy);} return @a;}   foreach (spiral 5) {printf "%3d", $_ foreach @$_; print "\n";}
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.
#Ruby
Ruby
class Array def radix_sort(base=10) ary = dup rounds = (Math.log(ary.minmax.map(&:abs).max)/Math.log(base)).floor + 1 rounds.times do |i| buckets = Array.new(2*base){[]} base_i = base**i ary.each do |n| digit = (n/base_i) % base digit += base if 0<=n buckets[digit] << n end ary = buckets.flatten p [i, ary] if $DEBUG end ary end def radix_sort!(base=10) replace radix_sort(base) end end   p [1, 3, 8, 9, 0, 0, 8, 7, 1, 6].radix_sort p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort p [170, 45, 75, 90, 2, 24, -802, -66].radix_sort p [100000, -10000, 400, 23, 10000].radix_sort
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.
#C.2B.2B
C++
#include <iterator> #include <algorithm> // for std::partition #include <functional> // for std::less   // helper function for median of three template<typename T> T median(T t1, T t2, T t3) { if (t1 < t2) { if (t2 < t3) return t2; else if (t1 < t3) return t3; else return t1; } else { if (t1 < t3) return t1; else if (t2 < t3) return t3; else return t2; } }   // helper object to get <= from < template<typename Order> struct non_strict_op: public std::binary_function<typename Order::second_argument_type, typename Order::first_argument_type, bool> { non_strict_op(Order o): order(o) {} bool operator()(typename Order::second_argument_type arg1, typename Order::first_argument_type arg2) const { return !order(arg2, arg1); } private: Order order; };   template<typename Order> non_strict_op<Order> non_strict(Order o) { return non_strict_op<Order>(o); }   template<typename RandomAccessIterator, typename Order> void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order) { if (first != last && first+1 != last) { typedef typename std::iterator_traits<RandomAccessIterator>::value_type value_type; RandomAccessIterator mid = first + (last - first)/2; value_type pivot = median(*first, *mid, *(last-1)); RandomAccessIterator split1 = std::partition(first, last, std::bind2nd(order, pivot)); RandomAccessIterator split2 = std::partition(split1, last, std::bind2nd(non_strict(order), pivot)); quicksort(first, split1, order); quicksort(split2, last, order); } }   template<typename RandomAccessIterator> void quicksort(RandomAccessIterator first, RandomAccessIterator last) { quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>()); }
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
#Pascal
Pascal
PatienceSortTask (Output);   CONST MaxSortSize = 1024; { A power of two. } MaxWinnersSize = (2 * MaxSortSize) - 1;   TYPE PilesArrayType = ARRAY [1 .. MaxSortSize] OF INTEGER; WinnersArrayType = ARRAY [1 .. MaxWinnersSize, 1 .. 2] OF INTEGER;   VAR ExampleNumbers : ARRAY [0 .. 35] OF INTEGER; SortedIndices : ARRAY [0 .. 25] OF INTEGER; i : INTEGER;   FUNCTION NextPowerOfTwo (n : INTEGER) : INTEGER; VAR Pow2 : INTEGER; BEGIN { This need not be a fast implementation. } Pow2 := 1; WHILE Pow2 < n DO Pow2 := Pow2 + Pow2; NextPowerOfTwo := Pow2; END;   PROCEDURE InitPilesArray (VAR Arr : PilesArrayType); VAR i : INTEGER; BEGIN FOR i := 1 TO MaxSortSize DO Arr[i] := 0; END;   PROCEDURE InitWinnersArray (VAR Arr : WinnersArrayType); VAR i : INTEGER; BEGIN FOR i := 1 TO MaxWinnersSize DO BEGIN Arr[i, 1] := 0; Arr[i, 2] := 0; END; END;   PROCEDURE IntegerPatienceSort (iFirst, iLast : INTEGER; Arr : ARRAY OF INTEGER; VAR Sorted : ARRAY OF INTEGER); VAR NumPiles : INTEGER; Piles, Links : PilesArrayType; Winners : WinnersArrayType;   FUNCTION FindPile (q : INTEGER) : INTEGER; { Bottenbruch search for the leftmost pile whose top is greater than or equal to some element 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 } VAR i, j, k, Index : INTEGER; BEGIN IF NumPiles = 0 THEN Index := 1 ELSE BEGIN j := 0; k := NumPiles - 1; WHILE j <> k DO BEGIN i := (j + k) DIV 2; IF Arr[Piles[j + 1] + iFirst - 1] < Arr[q + iFirst - 1] THEN j := i + 1 ELSE k := i END; IF j = NumPiles - 1 THEN BEGIN IF Arr[Piles[j + 1] + iFirst - 1] < Arr[q + iFirst - 1] THEN { A new pile is needed. } j := j + 1 END; Index := j + 1 END; FindPile := Index END;   PROCEDURE Deal; VAR i, q : INTEGER; BEGIN FOR q := 1 TO iLast - iFirst + 1 DO BEGIN i := FindPile (q); Links[q] := Piles[i]; Piles[i] := q; IF i = NumPiles + 1 THEN NumPiles := i END END;   PROCEDURE KWayMerge; { 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 array, and one can find an opponent quickly by simply toggling the least significant bit of a competitor's array index. } VAR TotalExternalNodes : INTEGER; TotalNodes : INTEGER; iSorted, i, Next : INTEGER;   FUNCTION FindOpponent (i : INTEGER) : INTEGER; VAR Opponent : INTEGER; BEGIN IF ODD (i) THEN Opponent := i - 1 ELSE Opponent := i + 1; FindOpponent := Opponent END;   FUNCTION PlayGame (i : INTEGER) : INTEGER; VAR j, iWinner : INTEGER; BEGIN j := FindOpponent (i); IF Winners[i, 1] = 0 THEN iWinner := j ELSE IF Winners[j, 1] = 0 THEN iWinner := i ELSE IF (Arr[Winners[j, 1] + iFirst - 1] < Arr[Winners[i, 1] + iFirst - 1]) THEN iWinner := j ELSE iWinner := i; PlayGame := iWinner END;   PROCEDURE ReplayGames (i : INTEGER); VAR j, iWinner : INTEGER; BEGIN j := i; WHILE j <> 1 DO BEGIN iWinner := PlayGame (j); j := j DIV 2; Winners[j, 1] := Winners[iWinner, 1]; Winners[j, 2] := Winners[iWinner, 2]; END END;   PROCEDURE BuildTree; VAR iStart, i, iWinner : INTEGER; BEGIN FOR i := 1 TO TotalExternalNodes DO { Record which pile a winner will have come from. } Winners[TotalExternalNodes - 1 + i, 2] := i;   FOR i := 1 TO NumPiles DO { The top of each pile becomes a starting competitor. } Winners[TotalExternalNodes + i - 1, 1] := Piles[i];   FOR i := 1 TO NumPiles DO { Discard the top of each pile. } Piles[i] := Links[Piles[i]];   iStart := TotalExternalNodes; WHILE iStart <> 1 DO BEGIN i := iStart; WHILE i <= (2 * iStart) - 1 DO BEGIN iWinner := PlayGame (i); Winners[i DIV 2, 1] := Winners[iWinner, 1]; Winners[i DIV 2, 2] := Winners[iWinner, 2]; i := i + 2 END; iStart := iStart DIV 2 END END;   BEGIN TotalExternalNodes := NextPowerOfTwo (NumPiles); TotalNodes := (2 * TotalExternalNodes) - 1; BuildTree; iSorted := 0; WHILE Winners[1, 1] <> 0 DO BEGIN Sorted[iSorted] := Winners[1, 1] + iFirst - 1; iSorted := iSorted + 1; i := Winners[1, 2]; Next := Piles[i]; { The next top of pile i. } IF Next <> 0 THEN Piles[i] := Links[Next]; { Drop that top. } i := (TotalNodes DIV 2) + i; Winners[i, 1] := Next; ReplayGames (i) END END;   BEGIN NumPiles := 0; InitPilesArray (Piles); InitPilesArray (Links); InitWinnersArray (Winners);   IF MaxSortSize < iLast - iFirst + 1 THEN BEGIN Write ('This subarray is too large for the program.'); WriteLn; HALT END ELSE BEGIN Deal; KWayMerge END END;   BEGIN ExampleNumbers[10] := 22; ExampleNumbers[11] := 15; ExampleNumbers[12] := 98; ExampleNumbers[13] := 82; ExampleNumbers[14] := 22; ExampleNumbers[15] := 4; ExampleNumbers[16] := 58; ExampleNumbers[17] := 70; ExampleNumbers[18] := 80; ExampleNumbers[19] := 38; ExampleNumbers[20] := 49; ExampleNumbers[21] := 48; ExampleNumbers[22] := 46; ExampleNumbers[23] := 54; ExampleNumbers[24] := 93; ExampleNumbers[25] := 8; ExampleNumbers[26] := 54; ExampleNumbers[27] := 2; ExampleNumbers[28] := 72; ExampleNumbers[29] := 84; ExampleNumbers[30] := 86; ExampleNumbers[31] := 76; ExampleNumbers[32] := 53; ExampleNumbers[33] := 37; ExampleNumbers[34] := 90;   IntegerPatienceSort (10, 34, ExampleNumbers, SortedIndices);   Write ('unsorted '); FOR i := 10 TO 34 DO BEGIN Write (' '); Write (ExampleNumbers[i]) END; WriteLn; Write ('sorted '); FOR i := 0 TO 24 DO BEGIN Write (' '); Write (ExampleNumbers[SortedIndices[i]]); END; WriteLn 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.
#BCPL
BCPL
get "libhdr"   let insertionSort(A, len) be for i = 1 to len-1 do $( let value = A!i let j = i-1 while j >= 0 & A!j > value do $( A!(j+1) := A!j j := j-1 $) A!(j+1) := value $)   let write(s, A, len) be $( writes(s) for i=0 to len-1 do writed(A!i, 4) wrch('*N') $)   let start() be $( let array = table 4,65,2,-31,0,99,2,83,782,1 let length = 10 write("Before: ", array, length) insertionSort(array, length) write("After: ", array, length) $)
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
#Scheme
Scheme
(define (insertions e list) (if (null? list) (cons (cons e list) list) (cons (cons e list) (map (lambda (tail) (cons (car list) tail)) (insertions e (cdr list))))))   (define (permutations list) (if (null? list) (cons list list) (apply append (map (lambda (permutation) (insertions (car list) permutation)) (permutations (cdr list))))))   (define (sorted? list) (cond ((null? list) #t) ((null? (cdr list)) #t) ((<= (car list) (cadr list)) (sorted? (cdr list))) (else #f)))   (define (permutation-sort list) (let loop ((permutations (permutations list))) (if (sorted? (car permutations)) (car permutations) (loop (cdr permutations)))))
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 Heapsort. 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) Heapsort is an in-place sorting algorithm with worst case and average complexity of   O(n logn). The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. A heap sort requires random access, so can only be used on an array-like data structure. Pseudocode: function heapSort(a, count) is input: an unordered array a of length count (first place a in max-heap order) heapify(a, count) end := count - 1 while end > 0 do (swap the root(maximum value) of the heap with the last element of the heap) swap(a[end], a[0]) (decrement the size of the heap so that the previous max value will stay in its proper place) end := end - 1 (put the heap back in max-heap order) siftDown(a, 0, end) function heapify(a,count) is (start is assigned the index in a of the last parent node) start := (count - 2) / 2 while start ≥ 0 do (sift down the node at index start to the proper place such that all nodes below the start index are in heap order) siftDown(a, start, count-1) start := start - 1 (after sifting down the root all nodes/elements are in heap order) function siftDown(a, start, end) is (end represents the limit of how far down the heap to sift) root := start while root * 2 + 1 ≤ end do (While the root has at least one child) child := root * 2 + 1 (root*2+1 points to the left child) (If the child has a sibling and the child's value is less than its sibling's...) if child + 1 ≤ end and a[child] < a[child + 1] then child := child + 1 (... then point to the right child instead) if a[root] < a[child] then (out of max-heap order) swap(a[root], a[child]) root := child (repeat to continue sifting down the child now) else return Write a function to sort a collection of integers using heapsort.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program heapSort.s */ /* look Pseudocode begin this task */   /************************************/ /* 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 1,3,6,2,5,9,10,8,4,7 #TableNumber: .int 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,#NBELEMENTS @ number of élements bl heapSort 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 /******************************************************************/ /* heap sort */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of element */ heapSort: push {r2,r3,r4,lr} @ save registers bl heapify @ first place table in max-heap order sub r3,r1,#1 1: cmp r3,#0 ble 100f mov r1,#0 @ swap the root(maximum value) of the heap with the last element of the heap) mov r2,r3 bl swapElement sub r3,#1 mov r1,#0 mov r2,r3 @ put the heap back in max-heap order bl siftDown b 1b   100: pop {r2,r3,r4,lr} bx lr @ return /******************************************************************/ /* place table in max-heap order */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of element */ heapify: push {r1,r2,r3,r4,lr} @ save registers mov r4,r1 sub r3,r1,#2 lsr r3,#1 1: cmp r3,#0 blt 100f mov r1,r3 sub r2,r4,#1 bl siftDown sub r3,#1 b 1b 100: pop {r1,r2,r3,r4,lr} bx lr @ return /******************************************************************/ /* swap two elements of table */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the first index */ /* r2 contains the second index */ swapElement: push {r3,r4,lr} @ save registers ldr r3,[r0,r1,lsl #2] @ swap number on the table ldr r4,[r0,r2,lsl #2] str r4,[r0,r1,lsl #2] str r3,[r0,r2,lsl #2]   100: pop {r3,r4,lr} bx lr @ return   /******************************************************************/ /* put the heap back in max-heap order */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the first index */ /* r2 contains the last index */ siftDown: push {r1-r7,lr} @ save registers @ r1 = root = start mov r3,r2 @ save last index 1: lsl r4,r1,#1 add r4,#1 cmp r4,r3 bgt 100f add r5,r4,#1 cmp r5,r3 bgt 2f ldr r6,[r0,r4,lsl #2] @ compare elements on the table ldr r7,[r0,r5,lsl #2] cmp r6,r7 movlt r4,r5 2: ldr r7,[r0,r4,lsl #2] @ compare elements on the table ldr r6,[r0,r1,lsl #2] @ root cmp r6,r7 bge 100f mov r2,r4 @ and r1 is root bl swapElement mov r1,r4 @ root = child b 1b   100: pop {r1-r7,lr} bx lr @ return   /******************************************************************/ /* Display table elements */ /******************************************************************/ /* r0 contains the address of table */ displayTable: push {r0-r3,lr} @ save registers mov r2,r0 @ table address mov r3,#0 1: @ loop display table ldr r0,[r2,r3,lsl #2] ldr r1,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/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.
#AppleScript
AppleScript
(* In-place, iterative binary merge sort Merge sort algorithm: John von Neumann, 1945.   Convenience terminology used here: run: one of two adjacent source-list ranges containing ordered items for merging. block: range in the destination list to which two runs are merged. *) on mergeSort(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}   -- Script object containing the input list and the sort range indices. script main property lst : theList property l : missing value property r : missing value end script set {main's l, main's r} to {l, r}   -- Just swap adjacent items as necessary on the first pass. -- (Short insertion sorts would be better, to create larger initial runs.) repeat with j from (l + 1) to r by 2 set i to j - 1 set lv to main's lst's item i set rv to main's lst's item j if (lv > rv) then set main's lst's item i to rv set main's lst's item j to lv end if end repeat set rangeLength to r - l + 1 if (rangeLength < 3) then return -- That's all if fewer than three items to sort.   -- Script object to alternate with the one above as the source and destination for the -- merges. Its list need only contain the items from the sort range as ordered so far. script aux property lst : main's lst's items l thru r property l : 1 property r : rangeLength end script   -- Work out how many merging passes will be needed and set the script objects' initial -- source and destination roles so that the final pass will merge back to the original list. set passesToDo to 0 set blockSize to 2 repeat while (blockSize < rangeLength) set passesToDo to passesToDo + 1 set blockSize to blockSize + blockSize end repeat set {srce, dest} to {{main, aux}, {aux, main}}'s item (passesToDo mod 2 + 1)   -- Do the remaining passes, doubling the run and block sizes on each pass. -- (The end set in each pass will usually be truncated.) set blockSize to 2 repeat passesToDo times -- Per pass. set runSize to blockSize set blockSize to blockSize + blockSize set k to (dest's l) - 1 -- Destination traversal index.   repeat with leftStart from srce's l to srce's r by blockSize -- Per merge. set blockEnd to k + blockSize if (blockEnd comes after dest's r) then set blockEnd to dest's r set i to leftStart -- Left run traversal index. set leftEnd to leftStart + runSize - 1 if (leftEnd comes before srce's r) then set j to leftEnd + 1 -- Right run traversal index. set rightEnd to leftEnd + runSize if (rightEnd comes after srce's r) then set rightEnd to srce's r -- Merge process: set lv to srce's lst's item i set rv to srce's lst's item j repeat with k from (k + 1) to blockEnd if (lv > rv) then set dest's lst's item k to rv if (j = rightEnd) then exit repeat -- Right run used up. set j to j + 1 set rv to srce's lst's item j else set dest's lst's item k to lv if (i = leftEnd) then -- Left run used up. set i to j exit repeat end if set i to i + 1 set lv to srce's lst's item i end if end repeat end if -- Use up the remaining items from the not-yet-exhausted run. repeat with k from (k + 1) to blockEnd set dest's lst's item k to srce's lst's item i set i to i + 1 end repeat end repeat -- Per merge.   -- Switch source and destination scripts for the next pass. tell srce set srce to dest set dest to it end tell end repeat -- Per pass.   return -- nothing end mergeSort property sort : mergeSort   -- Demo: local aList set aList to {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} sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. return aList
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.
#Kotlin
Kotlin
fun pancakeSort(a: IntArray) { /** Returns the index of the highest number in the range 0 until n. */ fun indexOfMax(n: Int): Int = (0 until n).maxByOrNull{ a[it] }!!   /** Flips the elements in the range 0 .. n. */ fun flip(index: Int) { a.reverse(0, index + 1) }   for (n in a.size downTo 2) { // successively reduce size of array by 1 val index = indexOfMax(n) // find index of largest if (index != n - 1) { // if it's not already at the end if (index > 0) { // if it's not already at the beginning flip(index) // move largest to beginning println("${a.contentToString()} after flipping first ${index + 1}") } flip(n - 1) // move largest to end println("${a.contentToString()} after flipping first $n") } } }   fun main() { val a = intArrayOf(7, 6, 9, 2, 4, 8, 1, 3, 5) println("${a.contentToString()} initially") pancakeSort(a) }
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.
#Lua
Lua
-- Initialisation math.randomseed(os.time()) numList = {step = 0, sorted = 0}   -- Create list of n random values function numList:build (n) self.values = {} for i = 1, n do self.values[i] = math.random(-100, 100) end end   -- Return boolean indicating whether the list is in order function numList:isSorted () for i = 2, #self.values do if self.values[i] < self.values[i - 1] then return false end end print("Finished!") return true end   -- Display list of numbers on one line function numList:show () if self.step == 0 then io.write("Initial state:\t") else io.write("After step " .. self.step .. ":\t") end for _, v in ipairs(self.values) do io.write(v .. " ") end print() end   -- Reverse n values from the left function numList:reverse (n) local flipped = {} for i, v in ipairs(self.values) do if i > n then flipped[i] = v else flipped[i] = self.values[n + 1 - i] end end self.values = flipped end   -- Perform one flip of a pancake sort function numList:pancake () local maxPos = 1 for i = 1, #self.values - self.sorted do if self.values[i] > self.values[maxPos] then maxPos = i end end if maxPos == 1 then numList:reverse(#self.values - self.sorted) self.sorted = self.sorted + 1 else numList:reverse(maxPos) end self.step = self.step + 1 end   -- Main procedure numList:build(10) numList:show() repeat numList:pancake() numList:show() until numList:isSorted()  
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
#PowerBASIC
PowerBASIC
%arraysize = 10   SUB stoogesort (L() AS LONG, i AS LONG, j AS LONG) IF L(j) < L(i) THEN SWAP L(i), L(j) IF (j - i) > 1 THEN DIM t AS LONG t = (j - i + 1) / 3 stoogesort L(), i, j - t stoogesort L(), i + t, j stoogesort L(), i, j - t END IF END SUB   FUNCTION PBMAIN () AS LONG RANDOMIZE TIMER   DIM x(%arraysize) AS LONG DIM i AS LONG, s AS STRING   s = "Before: " FOR i = 0 TO %arraysize x(i) = INT(RND * 100) s = s & STR$(x(i)) & " " NEXT   stoogesort x(), 0, %arraysize   #IF %DEF(%PB_CC32) PRINT s s = "" #ELSE s = s & $CRLF #ENDIF   s = s & "After: " FOR i = 0 TO %arraysize s = s & STR$(x(i)) & " " NEXT    ? s END FUNCTION
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
#PowerShell
PowerShell
Function StoogeSort( [Int32[]] $L ) { $i = 0 $j = $L.length-1 if( $L[$j] -lt $L[$i] ) { $L[$i] = $L[$i] -bxor $L[$j] $L[$j] = $L[$i] -bxor $L[$j] $L[$i] = $L[$i] -bxor $L[$j] } if( $j -gt 1 ) { $t = [int] ( ( $j + 1 ) / 3 ) $k = $j - $t + 1 [Array]::Copy( [Int32[]] ( StoogeSort( $L[0..( $j - $t ) ] ) ), $L, $k ) [Array]::ConstrainedCopy( [Int32[]] ( StoogeSort( $L[$t..$j ] ) ), 0, $L, $t, $k ) [Array]::Copy( [Int32[]] ( StoogeSort( $L[0..( $j - $t ) ] ) ), $L, $k ) } $L }   StoogeSort 9, 7, 5, 3, 1, 2, 4, 6, 8
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].
#Haxe
Haxe
class SelectionSort { @:generic public static function sort<T>(arr:Array<T>) { var len = arr.length; for (index in 0...len) { var minIndex = index; for (remainingIndex in (index+1)...len) { if (Reflect.compare(arr[minIndex], arr[remainingIndex]) > 0) minIndex = remainingIndex; } if (index != minIndex) { var temp = arr[index]; arr[index] = arr[minIndex]; arr[minIndex] = temp; } } } }   class Main { static function main() { var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0.0, -4.1, -9.5]; var stringArray = ['We', 'hold', 'these', 'truths', 'to', 'be', 'self-evident', 'that', 'all', 'men', 'are', 'created', 'equal']; Sys.println('Unsorted Integers:' + integerArray); SelectionSort.sort(integerArray); Sys.println('Sorted Integers: ' + integerArray); Sys.println('Unsorted Floats: ' + floatArray); SelectionSort.sort(floatArray); Sys.println('Sorted Floats: ' + floatArray); Sys.println('Unsorted Strings: ' + stringArray); SelectionSort.sort(stringArray); Sys.println('Sorted Strings: ' + stringArray); } }
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].
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string demosort(selectionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") end     procedure selectionsort(X,op) #: return sorted list ascending(or descending) local i,m   op := sortop(op,X) # select how and what we sort every i := 1 to *X-1 do { m := i every j := i + 1 to *X do if op(X[j],X[m]) then m := j # find X that belongs @i low (or high) X[m ~= i] :=: X[m] } return X 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.
#JavaScript
JavaScript
var soundex = function (s) { var a = s.toLowerCase().split('') f = a.shift(), r = '', codes = { a: '', e: '', i: '', o: '', u: '', b: 1, f: 1, p: 1, v: 1, c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2, d: 3, t: 3, l: 4, m: 5, n: 5, r: 6 };   r = f + a .map(function (v, i, a) { return codes[v] }) .filter(function (v, i, a) { return ((i === 0) ? v !== codes[f] : v !== a[i - 1]); }) .join('');   return (r + '000').slice(0, 4).toUpperCase(); };   var tests = { "Soundex": "S532", "Example": "E251", "Sownteks": "S532", "Ekzampul": "E251", "Euler": "E460", "Gauss": "G200", "Hilbert": "H416", "Knuth": "K530", "Lloyd": "L300", "Lukasiewicz": "L222", "Ellery": "E460", "Ghosh": "G200", "Heilbronn": "H416", "Kant": "K530", "Ladd": "L300", "Lissajous": "L222", "Wheaton": "W350", "Ashcraft": "A226", "Burroughs": "B622", "Burrows": "B620", "O'Hara": "O600" };   for (var i in tests) if (tests.hasOwnProperty(i)) { console.log( i + ' \t' + tests[i] + '\t' + soundex(i) + '\t' + (soundex(i) === tests[i]) ); }   // Soundex S532 S532 true // Example E251 E251 true // Sownteks S532 S532 true // Ekzampul E251 E251 true // Euler E460 E460 true // Gauss G200 G200 true // Hilbert H416 H416 true // Knuth K530 K530 true // Lloyd L300 L300 true // Lukasiewicz L222 L222 true // Ellery E460 E460 true // Ghosh G200 G200 true // Heilbronn H416 H416 true // Kant K530 K530 true // Ladd L300 L300 true // Lissajous L222 L222 true // Wheaton W350 W350 true // Ashcraft A226 A226 true // Burroughs B622 B622 true // Burrows B620 B620 true // O'Hara O600 O600 true
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.
#Perl
Perl
sub shell_sort { my (@a, $h, $i, $j, $k) = @_; for ($h = @a; $h = int $h / 2;) { for $i ($h .. $#a) { $k = $a[$i]; for ($j = $i; $j >= $h && $k < $a[$j - $h]; $j -= $h) { $a[$j] = $a[$j - $h]; } $a[$j] = $k; } } @a; }   my @a = map int rand 100, 1 .. $ARGV[0] || 10; say "@a"; @a = shell_sort @a; say "@a";  
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
#Nanoquery
Nanoquery
class Stack declare internalList   // constructor def Stack() internalList = list() end   def push(val) internalList.append(val) end   def pop() val = internalList[int(len($internalList) - 1)] internalList.remove(val)   return val end   def empty() return len(internalList) = 0 end 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)
#Phix
Phix
with javascript_semantics integer n = 6, x = 1, y = 0, counter = 0, len = n, dx = 0, dy = 1 string fmt = sprintf("%%%dd",length(sprintf("%d",n*n))) sequence m = repeat(repeat("??",n),n) for i=1 to 2*n do -- 2n runs.. for j=1 to len do -- of a length... x += dx y += dy m[x][y] = sprintf(fmt,counter) counter += 1 end for len -= odd(i) -- ..-1 every other {dx,dy} = {dy,-dx} -- in new direction end for printf(1,"%s\n",{join(apply(m,join),"\n")})
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.
#Rust
Rust
  fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) { let (left, right) = out.split_at_mut(in1.len()); left.clone_from_slice(in1); right.clone_from_slice(in2); }   // least significant digit radix sort fn radix_sort(data: &mut [i32]) { for bit in 0..31 { // types of small and big is Vec<i32>. // It will be infered from the next call of merge function. let (small, big): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| (x >> bit) & 1 == 0); merge(&small, &big, data); } // last bit is sign let (negative, positive): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| x < 0); merge(&negative, &positive, data); }   fn main() { let mut data = [170, 45, 75, -90, -802, 24, 2, 66, -17, 2]; println!("Before: {:?}", data); radix_sort(&mut data); println!("After: {:?}", 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.
#Scala
Scala
object RadixSort extends App { def sort(toBeSort: Array[Int]): Array[Int] = { // Loop for every bit in the integers var arr = toBeSort for (shift <- Integer.SIZE - 1 until -1 by -1) { // The array to put the partially sorted array into val tmp = new Array[Int](arr.length) // The number of 0s var j = 0 // Move the 0s to the new array, and the 1s to the old one for (i <- arr.indices) // If there is a 1 in the bit we are testing, the number will be negative // If this is the last bit, negative numbers are actually lower if ((shift == 0) == (arr(i) << shift >= 0)) arr(i - j) = arr(i) else { tmp(j) = arr(i) j += 1 } // Copy over the 1s from the old array arr.copyToArray(tmp, j, arr.length - j)   // And now the tmp array gets switched for another round of sorting arr = tmp } arr }   println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", ")) }
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.
#Clojure
Clojure
(defn qsort [L] (if (empty? L) '() (let [[pivot & L2] L] (lazy-cat (qsort (for [y L2 :when (< y pivot)] y)) (list pivot) (qsort (for [y L2 :when (>= y pivot)] y))))))
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
#Perl
Perl
sub patience_sort { my @s = [shift]; for my $card (@_) { my @t = grep { $_->[-1] > $card } @s; if (@t) { push @{shift(@t)}, $card } else { push @s, [$card] } } my @u; while (my @v = grep @$_, @s) { my $value = (my $min = shift @v)->[-1]; for (@v) { ($min, $value) = ($_, $_->[-1]) if $_->[-1] < $value } push @u, pop @$min; } return @u }   print join ' ', patience_sort qw(4 3 6 2 -1 13 12 9);  
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.
#C
C
#include <stdio.h>   void insertion_sort(int*, const size_t);   void insertion_sort(int *a, const size_t n) { for(size_t i = 1; i < n; ++i) { int key = a[i]; size_t j = i; while( (j > 0) && (key < a[j - 1]) ) { a[j] = a[j - 1]; --j; } a[j] = key; } }   int main (int argc, char** argv) {   int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};   const size_t n = sizeof(a) / sizeof(a[0]) ; // array extent   for (size_t i = 0; i < n; i++) printf("%d%s", a[i], (i == (n - 1))? "\n" : " ");   insertion_sort(a, n);   for (size_t i = 0; i < n; i++) printf("%d%s", a[i], (i == (n - 1))? "\n" : " ");   return 0; }  
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
#Sidef
Sidef
func psort(x, d=x.end) {   if (d.is_zero) { for i in (1 .. x.end) { (x[i] < x[i-1]) && return false; } return true; }   (d+1).times { x.prepend(x.splice(d, 1)...); x[d] < x[d-1] && next; psort(x, d-1) && return true; }   return false; }   var a = 10.of { 100.irand }; say "Before:\t#{a}"; psort(a); say "After:\t#{a}";
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
#Tcl
Tcl
package require Tcl 8.5 package require struct::list   proc inorder {list} {::tcl::mathop::<= {*}$list}   proc permutationsort {list} { while { ! [inorder $list]} { set list [struct::list nextperm $list] } return $list }
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 Heapsort. 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) Heapsort is an in-place sorting algorithm with worst case and average complexity of   O(n logn). The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. A heap sort requires random access, so can only be used on an array-like data structure. Pseudocode: function heapSort(a, count) is input: an unordered array a of length count (first place a in max-heap order) heapify(a, count) end := count - 1 while end > 0 do (swap the root(maximum value) of the heap with the last element of the heap) swap(a[end], a[0]) (decrement the size of the heap so that the previous max value will stay in its proper place) end := end - 1 (put the heap back in max-heap order) siftDown(a, 0, end) function heapify(a,count) is (start is assigned the index in a of the last parent node) start := (count - 2) / 2 while start ≥ 0 do (sift down the node at index start to the proper place such that all nodes below the start index are in heap order) siftDown(a, start, count-1) start := start - 1 (after sifting down the root all nodes/elements are in heap order) function siftDown(a, start, end) is (end represents the limit of how far down the heap to sift) root := start while root * 2 + 1 ≤ end do (While the root has at least one child) child := root * 2 + 1 (root*2+1 points to the left child) (If the child has a sibling and the child's value is less than its sibling's...) if child + 1 ≤ end and a[child] < a[child + 1] then child := child + 1 (... then point to the right child instead) if a[root] < a[child] then (out of max-heap order) swap(a[root], a[child]) root := child (repeat to continue sifting down the child now) else return Write a function to sort a collection of integers using heapsort.
#Arturo
Arturo
siftDown: function [items, start, ending][ root: start a: new items while [ending > 1 + 2 * root][ child: 1 + 2 * root if and? ending > child + 1 a\[child+1] > a\[child] -> child: child + 1   if? a\[root] < a\[child][ tmp: a\[child] a\[child]: a\[root] a\[root]: tmp root: child ] else -> return a ] return a ]   heapSort: function [items][ b: new items count: size b loop ((count-2)/2) .. 0 'start -> b: siftDown b start count loop (count-1) .. 1 'ending [ tmp: b\[ending] b\[ending]: b\0 b\0: tmp b: siftDown b 0 ending ] return b ]   print heapSort [3 1 2 8 5 7 9 4 6]
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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program mergeSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 #TableNumber: .int 1,11,3,6,2,5,9,10,8,4,7 TableNumber: .int 10,9,8,7,6,5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 4 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   ldr r0,iAdrTableNumber @ address number table mov r1,#0 @ first element mov r2,#NBELEMENTS @ number of élements bl mergeSort 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 1f ldr r0,iAdrszMessSortNok @ no !! error sort bl affichageMess b 100f 1: @ yes ldr r0,iAdrszMessSortOk bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrTableNumber: .int TableNumber iAdrszMessSortOk: .int szMessSortOk iAdrszMessSortNok: .int szMessSortNok /******************************************************************/ /* control sorted table */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of elements > 0 */ /* r0 return 0 if not sorted 1 if sorted */ isSorted: push {r2-r4,lr} @ save registers mov r2,#0 ldr r4,[r0,r2,lsl #2] 1: add r2,#1 cmp r2,r1 movge r0,#1 bge 100f ldr r3,[r0,r2, lsl #2] cmp r3,r4 movlt r0,#0 blt 100f mov r4,r3 b 1b 100: pop {r2-r4,lr} bx lr @ return   /******************************************************************/ /* merge */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains first start index /* r2 contains second start index */ /* r3 contains the last index */ merge: push {r1-r8,lr} @ save registers mov r5,r2 @ init index r2->r5 1: @ begin loop first section ldr r6,[r0,r1,lsl #2] @ load value first section index r1 ldr r7,[r0,r5,lsl #2] @ load value second section index r5 cmp r6,r7 ble 3f @ <= -> location first section OK str r7,[r0,r1,lsl #2] @ store value second section in first section add r8,r5,#1 cmp r8,r3 @ end second section ? strgt r6,[r0,r5,lsl #2] bgt 3f @ loop 2: @ loop insert element part 1 into part 2 sub r4,r8,#1 ldr r7,[r0,r8,lsl #2] @ load value 2 cmp r6,r7 @ value < strlt r6,[r0,r4,lsl #2] @ store value blt 3f str r7,[r0,r4,lsl #2] @ store value 2 add r8,#1 cmp r8,r3 @ end second section ? ble 2b @ no loop sub r8,#1 str r6,[r0,r8,lsl #2] @ store value 1 3: add r1,#1 cmp r1,r2 @ end first section ? blt 1b   100: pop {r1-r8,lr} bx lr @ return /******************************************************************/ /* merge sort */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the index of first element */ /* r2 contains the number of element */ mergeSort: push {r3-r7,lr} @ save registers cmp r2,#2 blt 100f lsr r4,r2,#1 @ number of element of each subset tst r2,#1 addne r4,#1 mov r5,r1 @ save first element mov r6,r2 @ save number of element mov r7,r4 @ save number of element of each subset mov r2,r4 bl mergeSort mov r1,r7 @ restaur number of element of each subset mov r2,r6 @ restaur number of element sub r2,r1 mov r3,r5 @ restaur first element add r1,r3 @ + 1 bl mergeSort @ sort first subset mov r1,r5 @ restaur first element mov r2,r7 @ restaur number of element of each subset add r2,r1 mov r3,r6 @ restaur number of element add r3,r1 sub r3,#1 @ last index bl merge 100: pop {r3-r7,lr} bx lr @ return   /******************************************************************/ /* Display table elements */ /******************************************************************/ /* r0 contains the address of table */ displayTable: push {r0-r3,lr} @ save registers mov r2,r0 @ table address mov r3,#0 1: @ loop display table ldr r0,[r2,r3,lsl #2] ldr r1,iAdrsZoneConv @ bl conversion10S @ décimal conversion ldr r0,iAdrsMessResult ldr r1,iAdrsZoneConv @ insert conversion bl strInsertAtCharInc bl affichageMess @ display message add r3,#1 cmp r3,#NBELEMENTS - 1 ble 1b ldr r0,iAdrszCarriageReturn bl affichageMess mov r0,r2 100: pop {r0-r3,lr} bx lr iAdrsZoneConv: .int sZoneConv /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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.
#Maple
Maple
flip := proc(arr, i) local start, temp, icopy; temp, start, icopy := 0,1,i: while (start < icopy) do arr[start], arr[icopy] := arr[icopy], arr[start]: start:=start+1: icopy:=icopy-1: end do: end proc: findMax := proc(arr, i) local Max, j: Max := 1: for j from 1 to i do if arr[j] > arr[Max] then Max := j: end if: end do: return Max: end proc: pancakesort := proc(arr) local len,i,Max; len := numelems(arr): for i from len to 2 by -1 do print(arr): Max := findMax(arr, i): if (not Max = i) then flip(arr, Max): flip(arr, i): end if: end do: print(arr); end proc:
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[LMaxPosition, Flip, pancakeSort] LMaxPosition[a_, n_] := With[{b = Take[a, n]}, First[Ordering[b, -1]]] SetAttributes[Flip, HoldAll]; Flip[a_] := Set[a, Reverse[a]] pancakeSort[in_] := Module[{n, lm, a = in, flips = 0}, Do[ lm = LMaxPosition[a, n]; If[lm < n, Flip[a[[;; lm]]]; Flip[a[[;; n]]]; ]; , {n, Length[a], 2, -1} ]; a ] pancakeSort[{6, 7, 8, 9, 2, 5, 3, 4, 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
#PureBasic
PureBasic
Procedure Stooge_Sort(Array L.i(1), i=0 , j=0) If j=0 j=ArraySize(L()) EndIf If L(i)>L(j) Swap L(i), L(j) EndIf If j-i>1 Protected t=(j-i+1)/3 Stooge_Sort(L(), i, j-t) Stooge_Sort(L(), i+t, j ) Stooge_Sort(L(), i, j-t) EndIf EndProcedure
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
#Python
Python
>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] >>> def stoogesort(L, i=0, j=None): if j is None: j = len(L) - 1 if L[j] < L[i]: L[i], L[j] = L[j], L[i] if j - i > 1: t = (j - i + 1) // 3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L   >>> stoogesort(data) [-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
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].
#Io
Io
List do ( selectionSortInPlace := method( size repeat(idx, swapIndices(idx, indexOf(slice(idx, size) min)) ) ) )   l := list(-1, 4, 2, -9) l selectionSortInPlace println # ==> list(-9, -1, 2, 4)
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].
#IS-BASIC
IS-BASIC
100 PROGRAM "SelecSrt.bas" 110 RANDOMIZE 120 NUMERIC ARRAY(-5 TO 14) 130 CALL INIT(ARRAY) 140 CALL WRITE(ARRAY) 150 CALL SELECTIONSORT(ARRAY) 160 CALL WRITE(ARRAY) 170 DEF INIT(REF A) 180 FOR I=LBOUND(A) TO UBOUND(A) 190 LET A(I)=RND(98)+1 200 NEXT 210 END DEF 220 DEF WRITE(REF A) 230 FOR I=LBOUND(A) TO UBOUND(A) 240 PRINT A(I); 250 NEXT 260 PRINT 270 END DEF 280 DEF SELECTIONSORT(REF A) 290 FOR I=LBOUND(A) TO UBOUND(A)-1 300 LET MN=A(I):LET INDEX=I 310 FOR J=I+1 TO UBOUND(A) 320 IF MN>A(J) THEN LET MN=A(J):LET INDEX=J 330 NEXT 340 LET A(INDEX)=A(I):LET A(I)=MN 350 NEXT 360 END DEF
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.
#Julia
Julia
  using Soundex @assert soundex("Ashcroft") == "A261" # true   # Too trivial? OK. Here is an example not using a package: function soundex(s) char2num = Dict('B'=>1,'F'=>1,'P'=>1,'V'=>1,'C'=>2,'G'=>2,'J'=>2,'K'=>2, 'Q'=>2,'S'=>2,'X'=>2,'Z'=>2,'D'=>3,'T'=>3,'L'=>4,'M'=>5,'N'=>5,'R'=>6) s = replace(s, r"[^a-zA-Z]", "") if s == "" return "" end ret = "$(uppercase(s[1]))" hadvowel = false lastletternum = haskey(char2num, ret[1]) ? char2num[ret[1]] : "" for c in s[2:end] c = uppercase(c) if haskey(char2num, c) letternum = char2num[c] if letternum != lastletternum || hadvowel ret = "$ret$letternum" lastletternum = letternum hadvowel = false end elseif c in ('A', 'E', 'I', 'O', 'U', 'Y') hadvowel = true end end while length(ret) < 4 ret *= "0" end ret[1:4] end @assert soundex("Ascroft") == "A261" @assert soundex("Euler") == "E460" @assert soundex("Gausss") == "G200" @assert soundex("Hilbert") == "H416" @assert soundex("Knuth") == "K530" @assert soundex("Lloyd") == "L300" @assert soundex("Lukasiewicz") == "L222" @assert soundex("Ellery") == "E460" @assert soundex("Ghosh") == "G200" @assert soundex("Heilbronn") == "H416" @assert soundex("Kant") == "K530" @assert soundex("Ladd") == "L300" @assert soundex("Lissajous") == "L222" @assert soundex("Wheaton") == "W350" @assert soundex("Ashcraft") == "A261" @assert soundex("Burroughs") == "B620" @assert soundex("Burrows") == "B620" @assert soundex("O'Hara") == "O600"  
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.
#Phix
Phix
with javascript_semantics function shell_sort(sequence s) integer gap = floor(length(s)/2), j while gap>0 do for i=gap to length(s) do object si = s[i] j = i-gap while j>=1 and si<=s[j] do s[j+gap] = s[j] j -= gap end while s[j+gap] = si end for gap = floor(gap/2) end while return s end function ?shell_sort(shuffle(tagset(10)))
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
#Nemerle
Nemerle
public class Stack[T] { private stack : list[T];   public this() { stack = []; }   public this(init : list[T]) { stack = init; }   public Push(item : T) : Stack[T] { Stack(item::stack) }   public Pop() : T * Stack[T] { (stack.Head, Stack(stack.Tail)) }   public Peek() : T { stack.Head }   public IsEmpty() : bool { stack.Length == 0 } }
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)
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de spiral (N) (prog1 (grid N N) (let (Dir '(north east south west .) This 'a1) (for Val (* N N) (=: val Val) (setq This (or (with ((car Dir) This) (unless (: val) This) ) (with ((car (setq Dir (cdr Dir))) This) (unless (: val) This) ) ) ) ) ) ) )   (mapc '((L) (for This L (prin (align 3 (: val)))) (prinl) ) (spiral 5) )
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.
#Scheme
Scheme
;;; An illustrative implementation of the radix-10 example at ;;; https://en.wikipedia.org/w/index.php?title=Radix_sort&oldid=1070890278#Least_significant_digit   (cond-expand (r7rs) (chicken (import (r7rs))))   (import (scheme base)) (import (scheme write))   (define (sort-by-decimal-digit data power-of-10) (define bins (make-vector 10 '())) (do ((i (- (vector-length data) 1) (- i 1))) ((= i -1)) (let* ((element (vector-ref data i)) (digit (truncate-remainder (truncate-quotient element power-of-10) 10))) (vector-set! bins digit (cons element (vector-ref bins digit))))) (let ((non-zero-found (let loop ((i 1)) (cond ((= i (vector-length bins)) #f) ((pair? (vector-ref bins i)) #t) (else (loop (+ i 1))))))) (when non-zero-found (let ((i 0)) (do ((j 0 (+ j 1))) ((= j (vector-length bins))) (do ((p (vector-ref bins j) (cdr p))) ((null? p)) (vector-set! data i (car p)) (set! i (+ i 1)))))) (not non-zero-found)))   (define (radix-sort data) (let loop ((power-of-10 1)) (let ((done (sort-by-decimal-digit data power-of-10))) (unless done (loop (* 10 power-of-10))))))   (define data (vector-copy #(170 45 75 90 2 802 2 66))) (write data) (newline) (radix-sort data) (write data) (newline)
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. quicksort RECURSIVE.   DATA DIVISION. LOCAL-STORAGE SECTION. 01 temp PIC S9(8).   01 pivot PIC S9(8).   01 left-most-idx PIC 9(5). 01 right-most-idx PIC 9(5).   01 left-idx PIC 9(5). 01 right-idx PIC 9(5).   LINKAGE SECTION. 78 Arr-Length VALUE 50.   01 arr-area. 03 arr PIC S9(8) OCCURS Arr-Length TIMES.   01 left-val PIC 9(5). 01 right-val PIC 9(5).   PROCEDURE DIVISION USING REFERENCE arr-area, OPTIONAL left-val, OPTIONAL right-val. IF left-val IS OMITTED OR right-val IS OMITTED MOVE 1 TO left-most-idx, left-idx MOVE Arr-Length TO right-most-idx, right-idx ELSE MOVE left-val TO left-most-idx, left-idx MOVE right-val TO right-most-idx, right-idx END-IF   IF right-most-idx - left-most-idx < 1 GOBACK END-IF   COMPUTE pivot = arr ((left-most-idx + right-most-idx) / 2)   PERFORM UNTIL left-idx > right-idx PERFORM VARYING left-idx FROM left-idx BY 1 UNTIL arr (left-idx) >= pivot END-PERFORM   PERFORM VARYING right-idx FROM right-idx BY -1 UNTIL arr (right-idx) <= pivot END-PERFORM   IF left-idx <= right-idx MOVE arr (left-idx) TO temp MOVE arr (right-idx) TO arr (left-idx) MOVE temp TO arr (right-idx)   ADD 1 TO left-idx SUBTRACT 1 FROM right-idx END-IF END-PERFORM   CALL "quicksort" USING REFERENCE arr-area, CONTENT left-most-idx, right-idx CALL "quicksort" USING REFERENCE arr-area, CONTENT left-idx, right-most-idx   GOBACK .
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
#Phix
Phix
with javascript_semantics function patience_sort(sequence s) -- create list of sorted lists sequence piles = {} for i=1 to length(s) do object n = s[i] for p=1 to length(piles)+1 do if p>length(piles) then piles = append(piles,{n}) elsif n>=piles[p][$] then piles[p] = append(deep_copy(piles[p]),n) exit end if end for end for -- merge sort the piles sequence res = "" while length(piles) do integer idx = smallest(piles,return_index:=true) res = append(res,piles[idx][1]) if length(piles[idx])=1 then piles[idx..idx] = {} else piles[idx] = piles[idx][2..$] end if end while return res end function constant tests = {{4,65,2,-31,0,99,83,782,1}, {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}, "nonzerosum", {"dog", "cow", "cat", "ape", "ant", "man", "pig", "ass", "gnu"}} for i=1 to length(tests) do pp(patience_sort(tests[i]),{pp_IntCh,false}) end for
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.
#C.23
C#
namespace Sort { using System;   static class InsertionSort<T> where T : IComparable { public static void Sort(T[] entries) { Sort(entries, 0, entries.Length - 1); }   public static void Sort(T[] entries, Int32 first, Int32 last) { for (var i = first + 1; i <= last; i++) { var entry = entries[i]; var j = i;   while (j > first && entries[j - 1].CompareTo(entry) > 0) entries[j] = entries[--j];   entries[j] = entry; } } } }
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
#Ursala
Ursala
#import std   permsort "p" = ~&ihB+ ordered"p"*~+ permutations   #cast %sL   example = permsort(lleq) <'pmf','oao','ejw','hhp','oqh','ock','dwj'>
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
#Wren
Wren
import "/sort" for Sort   var a = [170, 45, 75, -90, -802, 24, 2, 66]   // recursive permutation generator var recurse recurse = Fn.new { |last| if (last <= 0) return Sort.isSorted(a) for (i in 0..last) { var t = a[i] a[i] = a[last] a[last] = t if (recurse.call(last - 1)) return true t = a[i] a[i] = a[last] a[last] = t } return false }   System.print("Unsorted: %(a)") var count = a.count if (count > 1 && !recurse.call(count-1)) Fiber.abort("Sorted permutation not found!") System.print("Sorted  : %(a)")
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 Heapsort. 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) Heapsort is an in-place sorting algorithm with worst case and average complexity of   O(n logn). The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. A heap sort requires random access, so can only be used on an array-like data structure. Pseudocode: function heapSort(a, count) is input: an unordered array a of length count (first place a in max-heap order) heapify(a, count) end := count - 1 while end > 0 do (swap the root(maximum value) of the heap with the last element of the heap) swap(a[end], a[0]) (decrement the size of the heap so that the previous max value will stay in its proper place) end := end - 1 (put the heap back in max-heap order) siftDown(a, 0, end) function heapify(a,count) is (start is assigned the index in a of the last parent node) start := (count - 2) / 2 while start ≥ 0 do (sift down the node at index start to the proper place such that all nodes below the start index are in heap order) siftDown(a, start, count-1) start := start - 1 (after sifting down the root all nodes/elements are in heap order) function siftDown(a, start, end) is (end represents the limit of how far down the heap to sift) root := start while root * 2 + 1 ≤ end do (While the root has at least one child) child := root * 2 + 1 (root*2+1 points to the left child) (If the child has a sibling and the child's value is less than its sibling's...) if child + 1 ≤ end and a[child] < a[child + 1] then child := child + 1 (... then point to the right child instead) if a[root] < a[child] then (out of max-heap order) swap(a[root], a[child]) root := child (repeat to continue sifting down the child now) else return Write a function to sort a collection of integers using heapsort.
#AutoHotkey
AutoHotkey
heapSort(a) { Local end end := %a%0 heapify(a,end) While end > 1 %a%%end% := (%a%1 "", %a%1 := %a%%end%) ,siftDown(a, 1, --end) }   heapify(a, count) { Local start start := count // 2 While start siftDown(a, start--, count) }   siftDown(a, start, end) { Local child, c1 While start*2 <= end { c1 := 1 + child := start*2 If (c1 <= end && %a%%child% < %a%%c1%) child := c1 If (%a%%start% < %a%%child%) %a%%start% := (%a%%child% "", %a%%child% := %a%%start%) ,start := child Else Return } }   a = 1,5,2,7,3,4,6,8,1 ; ----- test ----- StringSplit a, a, `, heapSort("a") ListVars MsgBox
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.
#Astro
Astro
fun mergesort(m): if m.lenght <= 1: return m let middle = floor m.lenght / 2 let left = merge(m[:middle]) let right = merge(m[middle-1:]);   fun merge(left, right): let result = [] while not (left.isempty or right.isempty): if left[1] <= right[1]: result.push! left.shift!() else: result.push! right.shift!() result.push! left.push! right   let arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] print mergesort 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.
#MATLAB_.2F_Octave
MATLAB / Octave
function list = pancakeSort(list)   for i = (numel(list):-1:2)   minElem = list(i); minIndex = i;   %Find the min element in the current subset of the list for j = (i:-1:1) if list(j) <= minElem minElem = list(j); minIndex = j; end end   %If the element is already in the correct position don't flip if i ~= minIndex   %First flip flips the min element in the stack to the top list(minIndex:-1:1) = list(1:minIndex);   %Second flip flips the min element into the correct position in %the stack list(i:-1:1) = list(1:i);   end end %for end %pancakeSort
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
#Quackery
Quackery
[ 2 * 3 /mod 0 > + ] is twothirds ( n --> n )   [ dup 0 peek over -1 peek 2dup > iff [ rot 0 poke -1 poke ] else 2drop ] is swapends ( [ --> [ )   [ swapends dup size 3 < if done dup size twothirds split swap recurse swap join dup size 3 / split recurse join dup size twothirds split swap recurse swap join ] is stoogesort ( [ --> [ )   [] 33 times [ 90 random 10 + join ] dup echo cr stoogesort echo
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
#R
R
stoogesort = function(vect) { i = 1 j = length(vect) if(vect[j] < vect[i]) vect[c(j, i)] = vect[c(i, j)] if(j - i > 1) { t = (j - i + 1) %/% 3 vect[i:(j - t)] = stoogesort(vect[i:(j - t)]) vect[(i + t):j] = stoogesort(vect[(i + t):j]) vect[i:(j - t)] = stoogesort(vect[i:(j - t)]) } vect }   v = sample(21, 20) k = stoogesort(v) v k
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].
#J
J
selectionSort=: verb define data=. y for_xyz. y do. temp=. xyz_index }. data nvidx=. xyz_index + temp i. <./ temp data=. ((xyz_index, nvidx) { data) (nvidx, xyz_index) } data end. 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].
#Java
Java
public static void sort(int[] nums){ for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ int smallest = Integer.MAX_VALUE; int smallestAt = currentPlace+1; for(int check = currentPlace; check<nums.length;check++){ if(nums[check]<smallest){ smallestAt = check; smallest = nums[check]; } } int temp = nums[currentPlace]; nums[currentPlace] = nums[smallestAt]; nums[smallestAt] = temp; } }
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.
#Kotlin
Kotlin
// version 1.1.2   fun getCode(c: Char) = when (c) { 'B', 'F', 'P', 'V' -> "1" 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z' -> "2" 'D', 'T' -> "3" 'L' -> "4" 'M', 'N' -> "5" 'R' -> "6" 'H', 'W' -> "-" else -> "" }   fun soundex(s: String): String { if (s == "") return "" val sb = StringBuilder().append(s[0].toUpperCase()) var prev = getCode(sb[0]) for (i in 1 until s.length) { val curr = getCode(s[i].toUpperCase()) if (curr != "" && curr != "-" && curr != prev) sb.append(curr) if (curr != "-") prev = curr } return sb.toString().padEnd(4, '0').take(4) }   fun main(args: Array<String>) { val pairs = arrayOf( "Ashcraft" to "A261", "Ashcroft" to "A261", "Gauss" to "G200", "Ghosh" to "G200", "Hilbert" to "H416", "Heilbronn" to "H416", "Lee" to "L000", "Lloyd" to "L300", "Moses" to "M220", "Pfister" to "P236", "Robert" to "R163", "Rupert" to "R163", "Rubin" to "R150", "Tymczak" to "T522", "Soundex" to "S532", "Example" to "E251" ) for (pair in pairs) { println("${pair.first.padEnd(9)} -> ${pair.second} -> ${soundex(pair.first) == pair.second}") } }
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.
#PHP
PHP
  function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $arr; }  
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
#NetRexx
NetRexx
/* NetRexx ************************************************************ * 13.08.2013 Walter Pachl translated from REXX version 2 **********************************************************************/ options replace format comments java crossref savelog symbols nobinary   stk = create_stk   say push(stk,123) 'from push' say empty(stk) say peek(stk) 'from peek' say pull(stk) 'from pull' say empty(stk) Say pull(stk) 'from pull'   method create_stk static returns Rexx stk = '' stk[0] = 0 return stk   method push(stk,v) static stk[0]=stk[0]+1 stk[stk[0]]=v Return v   method peek(stk) static x=stk[0] If x=0 Then Return 'stk is empty' Else Return stk[x]   method pull(stk) static x=stk[0] If x=0 Then Return 'stk is empty' Else Do stk[0]=stk[0]-1 Return stk[x] End   method empty(stk) static Return stk[0]=0
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)
#PL.2FI
PL/I
/* Generates a square matrix containing the integers from 0 to N**2-1, */ /* where N is the length of one side of the square. */ /* Written 22 February 2010. */ declare n fixed binary;   put skip list ('Please type the size of the square:'); get list (n);   begin; declare A(n,n) fixed binary; declare (i, j, iinc, jinc, q) fixed binary;   A = -1;   i, j = 1; iinc = 0; jinc = 1; do q = 0 to n**2-1; if a(i,j) < 0 then a(i,j) = q; else do; /* back up */ j = j -jinc; i = i - iinc; /* change direction */ if iinc = 0 & jinc = 1 then do; iinc = 1; jinc = 0; end; else if iinc = 1 & jinc = 0 then do; iinc = 0; jinc = -1; end; else if iinc = 0 & jinc = -1 then do; iinc = -1; jinc = 0; end; else if iinc = -1 & jinc = 0 then do; iinc = 0; jinc = 1; end; /* Take one step in the new direction */ i = i + iinc; j = j + jinc; a(i,j) = q; end; if i+iinc > n | i+iinc < 1 then do; iinc = 0; jinc = 1; if j+1 > n then jinc = -1; else if j-1 < 1 then jinc = 1; if a(i+iinc,j+jinc) >= 0 then jinc = -jinc; /* j = j + jinc; /* to move on from the present (filled) position */ end; else i = i + iinc; if j+jinc > n | j+jinc < 1 then do; jinc = 0; iinc = 1; if i+1 > n then iinc = -1; else if i-1 < 1 then iinc = 1; if a(i+iinc,j+jinc) >= 0 then iinc = -iinc; i = i + iinc; /* to move on from the present (filled) position */ end; else j = j + jinc; end;   /* Display the square. */ do i = 1 to n; put skip edit (A(i,*)) (F(4)); end;   end;
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.
#Sidef
Sidef
class Array { method radix_sort(base=10) { var arr = self.clone var rounds = ([arr.minmax].map{.abs}.max.ilog(base) + 1) for i in (0..rounds) { var buckets = (2*base -> of {[]}) var base_i = base**i for n in arr { var digit = (n/base_i % base) digit += base if (0 <= n) buckets[digit].append(n) } arr = buckets.flat } return arr } }   for arr in [ [1, 3, 8, 9, 0, 0, 8, 7, 1, 6], [170, 45, 75, 90, 2, 24, 802, 66], [170, 45, 75, 90, 2, 24, -802, -66], [100000, -10000, 400, 23, 10000], ] { say arr.radix_sort }
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.
#CoffeeScript
CoffeeScript
  quicksort = ([x, xs...]) -> return [] unless x? smallerOrEqual = (a for a in xs when a <= x) larger = (a for a in xs when a > x) (quicksort smallerOrEqual).concat(x).concat(quicksort larger)  
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
#PHP
PHP
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } }   function patience_sort(&$n) { $piles = array(); // sort into piles foreach ($n as $x) { // binary search $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); }   // priority queue allows us to merge piles efficiently $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); }   $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($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.
#C.2B.2B
C++
g++ -std=c++11 insertion.cpp
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
#zkl
zkl
rns:=T(4, 65, 2, 31, 0, 99, 2, 83, 782, 1); fcn psort(list){ len:=list.len(); cnt:=Ref(0); foreach ns in (Utils.Helpers.permuteW(list)){ // lasy permutations cnt.set(1); ns.reduce('wrap(p,n){ if(p>n)return(Void.Stop); cnt.inc(); n }); if(cnt.value==len) return(ns); } }(rns).println();
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 Heapsort. 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) Heapsort is an in-place sorting algorithm with worst case and average complexity of   O(n logn). The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. A heap sort requires random access, so can only be used on an array-like data structure. Pseudocode: function heapSort(a, count) is input: an unordered array a of length count (first place a in max-heap order) heapify(a, count) end := count - 1 while end > 0 do (swap the root(maximum value) of the heap with the last element of the heap) swap(a[end], a[0]) (decrement the size of the heap so that the previous max value will stay in its proper place) end := end - 1 (put the heap back in max-heap order) siftDown(a, 0, end) function heapify(a,count) is (start is assigned the index in a of the last parent node) start := (count - 2) / 2 while start ≥ 0 do (sift down the node at index start to the proper place such that all nodes below the start index are in heap order) siftDown(a, start, count-1) start := start - 1 (after sifting down the root all nodes/elements are in heap order) function siftDown(a, start, end) is (end represents the limit of how far down the heap to sift) root := start while root * 2 + 1 ≤ end do (While the root has at least one child) child := root * 2 + 1 (root*2+1 points to the left child) (If the child has a sibling and the child's value is less than its sibling's...) if child + 1 ≤ end and a[child] < a[child + 1] then child := child + 1 (... then point to the right child instead) if a[root] < a[child] then (out of max-heap order) swap(a[root], a[child]) root := child (repeat to continue sifting down the child now) else return Write a function to sort a collection of integers using heapsort.
#BBC_BASIC
BBC BASIC
DIM test(9) test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 PROCheapsort(test()) FOR i% = 0 TO 9 PRINT test(i%) ; NEXT PRINT END   DEF PROCheapsort(a()) LOCAL e% PROCheapify(a()) FOR e% = DIM(a(),1) TO 1 STEP -1 SWAP a(e%), a(0) PROCsiftdown(a(), 0, e%-1) NEXT ENDPROC   DEF PROCheapify(a()) LOCAL s%, m% m% = DIM(a(),1) FOR s% = (m% - 1) / 2 TO 0 STEP -1 PROCsiftdown(a(), s%, m%) NEXT ENDPROC   DEF PROCsiftdown(a(), s%, e%) LOCAL c%, r% r% = s% WHILE r% * 2 + 1 <= e% c% = r% * 2 + 1 IF c% + 1 <= e% IF a(c%) < a(c% + 1) c% += 1 IF a(r%) < a(c%) SWAP a(r%), a(c%) : r% = c% ELSE ENDPROC ENDWHILE ENDPROC
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 Heapsort. 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) Heapsort is an in-place sorting algorithm with worst case and average complexity of   O(n logn). The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. A heap sort requires random access, so can only be used on an array-like data structure. Pseudocode: function heapSort(a, count) is input: an unordered array a of length count (first place a in max-heap order) heapify(a, count) end := count - 1 while end > 0 do (swap the root(maximum value) of the heap with the last element of the heap) swap(a[end], a[0]) (decrement the size of the heap so that the previous max value will stay in its proper place) end := end - 1 (put the heap back in max-heap order) siftDown(a, 0, end) function heapify(a,count) is (start is assigned the index in a of the last parent node) start := (count - 2) / 2 while start ≥ 0 do (sift down the node at index start to the proper place such that all nodes below the start index are in heap order) siftDown(a, start, count-1) start := start - 1 (after sifting down the root all nodes/elements are in heap order) function siftDown(a, start, end) is (end represents the limit of how far down the heap to sift) root := start while root * 2 + 1 ≤ end do (While the root has at least one child) child := root * 2 + 1 (root*2+1 points to the left child) (If the child has a sibling and the child's value is less than its sibling's...) if child + 1 ≤ end and a[child] < a[child + 1] then child := child + 1 (... then point to the right child instead) if a[root] < a[child] then (out of max-heap order) swap(a[root], a[child]) root := child (repeat to continue sifting down the child now) else return Write a function to sort a collection of integers using heapsort.
#BCPL
BCPL
// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10.   GET "libhdr.h"   LET heapify(v, k, i, last) BE { LET j = i+i // If there is a son (or two), j = subscript of first. AND x = k // x will hold the larger of the sons if any.   IF j<=last DO x := v!j // j, x = subscript and key of first son. IF j< last DO { LET y = v!(j+1) // y = key of the other son. IF x<y DO x,j := y, j+1 // j, x = subscript and key of larger son. }   IF k>=x DO { v!i := k // k is not lower than larger son if any. RETURN } v!i := x i := j } REPEAT   AND heapsort(v, upb) BE { FOR i = upb/2 TO 1 BY -1 DO heapify(v, v!i, i, upb)   FOR i = upb TO 2 BY -1 DO { LET k = v!i v!i := v!1 heapify(v, k, 1, i-1) } }   LET start() = VALOF { LET v = VEC 1000 FOR i = 1 TO 1000 DO v!i := randno(1_000_000) heapsort(v, 1000) FOR i = 1 TO 1000 DO { IF i MOD 10 = 0 DO newline() writef(" %i6", v!i) } newline() }
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.
#ATS
ATS
(*------------------------------------------------------------------*) (* Mergesort in ATS2, for linear lists. *) (*------------------------------------------------------------------*)   #include "share/atspre_staload.hats"   staload UN = "prelude/SATS/unsafe.sats"   #define NIL list_vt_nil () #define :: list_vt_cons   (*------------------------------------------------------------------*)   (* Destructive stable merge. *) extern fun {a : vt@ype} list_vt_merge {m, n : int} (lst1 : list_vt (a, m), lst2 : list_vt (a, n))  :<!wrt> list_vt (a, m + n)   (* Order predicate for list_vt_merge. You have to implement this to suit your needs. *) extern fun {a : vt@ype} list_vt_merge$lt : (&a, &a) -<> bool   (* Destructive stable mergesort. *) extern fun {a : vt@ype} list_vt_mergesort {n  : int} (lst : list_vt (a, n))  :<!wrt> list_vt (a, n)   (* Order predicate for list_vt_mergesort. You have to implement this to suit your needs. *) extern fun {a : vt@ype} list_vt_mergesort$lt : (&a, &a) -<> bool   (*------------------------------------------------------------------*)   implement {a} list_vt_merge {m, n} (lst1, lst2) = let macdef lt = list_vt_merge$lt<a>   fun loop {m, n  : nat} .<m + n>. (lst1  : list_vt (a, m), lst2  : list_vt (a, n), lst_merged : &List_vt a? >> list_vt (a, m + n))  :<!wrt> void = case+ lst1 of | ~ NIL => lst_merged := lst2 | @ elem1 :: tail1 => begin case+ lst2 of | ~ NIL => let prval () = fold@ lst1 in lst_merged := lst1 end | @ elem2 :: tail2 => if ~(elem2 \lt elem1) then let val () = lst_merged := lst1 prval () = fold@ lst2 val () = loop (tail1, lst2, tail1) prval () = fold@ lst_merged in end else let val () = lst_merged := lst2 prval () = fold@ lst1 val () = loop (lst1, tail2, tail2) prval () = fold@ lst_merged in end end   prval () = lemma_list_vt_param lst1 (* Proves 0 <= m. *) prval () = lemma_list_vt_param lst2 (* Proves 0 <= n. *) prval () = prop_verify {0 <= m} () prval () = prop_verify {0 <= n} ()   var lst_merged : List_vt a? val () = loop {m, n} (lst1, lst2, lst_merged) in lst_merged end   (*------------------------------------------------------------------*)   implement {a} list_vt_mergesort {n} lst = let implement list_vt_merge$lt<a> (x, y) = list_vt_mergesort$lt<a> (x, y)   (* You can make SMALL larger than 1 and write small_sort as a fast stable sort for small lists. *) #define SMALL 1 fn small_sort {m  : pos | m <= SMALL} (lst : list_vt (a, m), m  : int m)  :<!wrt> list_vt (a, m) = lst   fun recurs {m  : pos} .<m>. (lst : list_vt (a, m), m  : int m)  :<!wrt> list_vt (a, m) = if m <= SMALL then small_sort (lst, m) else let prval () = prop_verify {2 <= m} () val i = m / 2 val @(lst1, lst2) = list_vt_split_at<a> (lst, i) val lst1 = recurs (lst1, i) val lst2 = recurs (lst2, m - i) in list_vt_merge<a> (lst1, lst2) end   prval () = lemma_list_vt_param lst (* Proves 0 <= n. *) prval () = prop_verify {0 <= n} () in case+ lst of | NIL => lst | _ :: _ => recurs (lst, length lst) end   (*------------------------------------------------------------------*)   extern fun list_vt_mergesort_int {n  : int} (lst : list_vt (int, n))  :<!wrt> list_vt (int, n)   implement list_vt_mergesort_int {n} lst = let implement list_vt_mergesort$lt<int> (x, y) = x < y in list_vt_mergesort<int> {n} lst end   implement main0 () = let val lst = $list_vt (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) val () = println! ("before : ", $UN.castvwtp1{List int} lst) val lst = list_vt_mergesort_int lst val () = println! ("after  : ", $UN.castvwtp1{List int} lst) in list_vt_free<int> lst end   (*------------------------------------------------------------------*)
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.
#MAXScript
MAXScript
fn flipArr arr index = ( local new = #() for i = index to 1 by -1 do ( append new arr[i] ) join new (for i in (index+1) to arr.count collect arr[i]) return new )   fn pancakeSort arr = ( if arr.count < 2 then return arr else ( for i = arr.count to 1 by -1 do ( local newArr = for n in 1 to i collect arr[n] local oldArr = for o in (i+1) to arr.count collect arr[o] local maxIndices = for m in 1 to (newArr.count) where (newArr[m] == amax newArr) collect m local lastMaxIndex = maxIndices[maxIndices.count] newArr = flipArr newArr lastMaxIndex newArr = flipArr newArr newArr.count arr = join newArr oldArr ) return 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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.util.List   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method pancakeSort(tlist = List, debug = (1 == 0)) private static returns List   if tlist.size() > 1 then do loop i_ = tlist.size() by -1 while i_ > 1 maxPos = 0 loop a_ = 0 while a_ < i_ if Rexx tlist.get(a_) > Rexx tlist.get(maxPos) then maxPos = a_ end a_ if maxPos = i_ - 1 then iterate i_ if maxPos > 0 then pancakeFlip(tlist, maxPos + 1, debug) pancakeFlip(tlist, i_, debug) end i_ end return tlist   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method pancakeFlip(tlist = List, offset, debug = (1 == 0)) private static returns List z_ = offset - 1 pl = 3 if debug then do plx = offset.length() if plx > pl then pl = plx say ' flip{1-'offset.right(pl, 0)'} Before:' tlist end loop i_ = 0 while i_ < z_ Collections.swap(tlist, i_, z_) z_ = z_ - 1 end i_ if debug then do say ' flip{1-'offset.right(pl, 0)'} After:' tlist end return tlist   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static   isTrue = (1 == 1) isFalse = \isTrue   parse arg debug . if '-debug'.abbrev(debug.lower(), 2) then debug = isTrue else debug = isFalse   lists = sampleData() loop il = 1 to lists[0] clist = words2list(lists[il]) say ' Input:' clist say 'Output:' pancakeSort(clist, debug) say end il   return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method sampleData() private static lists = '' i_ = 0 i_ = i_ + 1; lists[0] = i_; lists[i_] = '1 4 3 5 2 9 8 7 6' i_ = i_ + 1; lists[0] = i_; lists[i_] = '10 -9 8 -7 6 -5 4 -3 2 -1 0 -10 9 -8 7 -6 5 -4 3 -2 1' i_ = i_ + 1; lists[0] = i_; lists[i_] = '88 18 31 44 4 0 8 81 14 78 20 76 84 33 73 75 82 5 62 70 12 7 1' i_ = i_ + 1; lists[0] = i_; lists[i_] = '10 10.0 10.00 1 -10.0 10. -1' i_ = i_ + 1; lists[0] = i_; lists[i_] = 'To be or not to be that is the question' i_ = i_ + 1; lists[0] = i_; lists[i_] = '1' return lists -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method words2list(wordlist) private static returns List   clist = ArrayList() loop w_ = 1 to wordlist.words() clist.add(wordlist.word(w_)) end w_   return clist  
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
#Racket
Racket
  #lang racket (define (stooge-sort xs [i 0] [j (- (vector-length xs) 1)]) (define (x i) (vector-ref xs i)) (define (x! i v) (vector-set! xs i v)) (define (swap! i j) (define t (x i)) (x! i (x j)) (x! j t)) (when (> (x i) (x j)) (swap! i j)) (when (> (- j i) 1) (define t (quotient (+ j (- i) 1) 3)) (stooge-sort xs i (- j t)) (stooge-sort xs (+ i t) j) (stooge-sort xs i (- j t))) xs)  
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
#Raku
Raku
sub stoogesort( @L, $i = 0, $j = @L.end ) { @L[$j,$i] = @L[$i,$j] if @L[$i] > @L[$j];   my $interval = $j - $i;   if $interval > 1 { my $t = ( $interval + 1 ) div 3; stoogesort( @L, $i , $j-$t ); stoogesort( @L, $i+$t, $j ); stoogesort( @L, $i , $j-$t ); } return @L; }   my @L = 1, 4, 5, 3, -6, 3, 7, 10, -2, -5;   stoogesort(@L).Str.say;  
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].
#JavaScript
JavaScript
function selectionSort(nums) { var len = nums.length; for(var i = 0; i < len; i++) { var minAt = i; for(var j = i + 1; j < len; j++) { if(nums[j] < nums[minAt]) minAt = j; }   if(minAt != i) { var temp = nums[i]; nums[i] = nums[minAt]; nums[minAt] = temp; } } return nums; }
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.
#Lua
Lua
local d, digits, alpha = '01230120022455012623010202', {}, ('A'):byte() d:gsub(".",function(c) digits[string.char(alpha)] = c alpha = alpha + 1 end)   function soundex(w) local res = {} for c in w:upper():gmatch'.'do local d = digits[c] if d then if #res==0 then res[1] = c elseif #res==1 or d~= res[#res] then res[1+#res] = d end end end if #res == 0 then return '0000' else res = table.concat(res):gsub("0",'') return (res .. '0000'):sub(1,4) end end   -- tests local tests = { {"", "0000"}, {"12346", "0000"}, {"he", "H000"}, {"soundex", "S532"}, {"example", "E251"}, {"ciondecks", "C532"}, {"ekzampul", "E251"}, {"résumé", "R250"}, {"Robert", "R163"}, {"Rupert", "R163"}, {"Rubin", "R150"}, {"Ashcraft", "A226"}, {"Ashcroft", "A226"} }   for i=1,#tests do local itm = tests[i] assert( soundex(itm[1])==itm[2] ) end print"all tests ok"
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.
#Picat
Picat
go => A = [23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78], println(A), shell_sort(A), println(A), nl.   % Inline sort shell_sort(A) => Inc = round(A.length/2), while (Inc > 0) foreach(I in Inc+1..A.length) Temp = A[I], J := I, while (J > Inc, A[J-Inc] > Temp) A[J] := A[J-Inc], J := J - Inc end, A[J] := Temp end, Inc := round(Inc/2.2) 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.
#PicoLisp
PicoLisp
(de shellSort (A) (for (Inc (*/ (length A) 2) (gt0 Inc) (*/ Inc 10 22)) (for (I Inc (get A I) (inc I)) (let (Tmp @ J I) (while (and (>= J Inc) (> (get A (- J Inc)) Tmp)) (set (nth A J) (get A (- J Inc))) (dec 'J Inc) ) (set (nth A J) Tmp) ) ) ) A )
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
#Nim
Nim
type Stack[T] = distinct seq[T]   func initStack[T](initialSize = 32): Stack[T] = Stack[T](newSeq[T](initialSize))   func isEmpty[T](stack: Stack[T]): bool = seq[T](stack).len == 0   func push[T](stack: var Stack[T]; item: sink T) = seq[T](stack).add(item)   func pop[T](stack: var Stack[T]): T = if stack.isEmpty: raise newException(IndexDefect, "stack is empty.") seq[T](stack).pop()   func top[T](stack: Stack[T]): T = if stack.isEmpty: raise newException(IndexDefect, "stack is empty.") seq[T](stack)[^1]   func mtop[T](stack: var Stack[T]): var T = if stack.isEmpty: raise newException(IndexDefect, "stack is empty.") seq[T](stack)[^1]   func `mtop=`[T](stack: var Stack[T]; value: T) = if stack.isEmpty: raise newException(IndexDefect, "stack is empty.") seq[T](stack)[^1] = value   when isMainModule:   var s = initStack[int]() s.push 2 echo s.pop s.push 3 echo s.top s.mtop += 1 echo s.top s.mtop = 5 echo s.top
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)
#PowerShell
PowerShell
function Spiral-Matrix ( [int]$N ) { # Initialize variables $X = 0 $Y = -1 $i = 0 $Sign = 1   # Intialize array $A = New-Object 'int[,]' $N, $N   # Set top row 1..$N | ForEach { $Y += $Sign; $A[$X,$Y] = ++$i }   # For each remaining half spiral... ForEach ( $M in ($N-1)..1 ) { # Set the vertical quarter spiral 1..$M | ForEach { $X += $Sign; $A[$X,$Y] = ++$i }   # Curve the spiral $Sign = -$Sign   # Set the horizontal quarter spiral 1..$M | ForEach { $Y += $Sign; $A[$X,$Y] = ++$i } }   # Convert the array to text output $Spiral = ForEach ( $X in 1..$N ) { ( 1..$N | ForEach { $A[($X-1),($_-1)] } ) -join "`t" }   return $Spiral }   Spiral-Matrix 5 "" Spiral-Matrix 7
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.
#Tailspin
Tailspin
  templates radixsort&{base:} sink bucketize def value: $; $ ~/ [email protected] -> # when <=0 ?($value <0..>)> do ..|@radixsort.positives: $value; when <=0> do ..|@radixsort.negatives(last): $value; otherwise def bucket: $ mod $base -> \(<?($value<0..>)> $ + 1 ! <=0> $base ! <> $ !\); ..|@radixsort.buckets($bucket): $value; @radixsort.done: 0; end bucketize // Negatives get completed in wrong length-order, we need to collect by length and correct at the end @: { done: 1, digit: 1"1", positives: [], negatives: [[]], buckets: [1..$base -> []]}; $... -> !bucketize [email protected] -> # when <=1> do [[email protected](last..1:-1)... ..., [email protected]...] ! otherwise def previous: [email protected]; ..|@: {done: 1, digit: [email protected] * $base, buckets:[1..$base -> []]}; ..|@.negatives: []; $previous... ... -> !bucketize [email protected] -> # end radixsort   [170, 45, 75, 91, 90, 92, 802, 24, 2, 66] -> radixsort&{base:10} -> !OUT::write ' ' -> !OUT::write [-170, -45, -91, -90, -92, -802, -24, -2, -76] -> radixsort&{base:10} -> !OUT::write ' ' -> !OUT::write [170, 45, 75, -91, -90, -92, -802, 24, 2, 66] -> radixsort&{base:10} -> !OUT::write ' ' -> !OUT::write [170, 45, 75, -91, -90, -92, -802, 24, 2, 66] -> radixsort&{base:3} -> !OUT::write  
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.
#Tcl
Tcl
package require Tcl 8.5 proc splitByRadix {lst base power} { # create a list of empty lists to hold the split by digit set out [lrepeat [expr {$base*2}] {}] foreach item $lst { # pulls the selected digit set digit [expr {($item / $base ** $power) % $base + $base * ($item >= 0)}] # append the number to the list selected by the digit lset out $digit [list {*}[lindex $out $digit] $item] } return $out }   # largest abs value element of a list proc tcl::mathfunc::maxabs {lst} { set max [abs [lindex $lst 0]] for {set i 1} {$i < [llength $lst]} {incr i} { set v [abs [lindex $lst $i]] if {$max < $v} {set max $v} } return $max }   proc radixSort {lst {base 10}} { # there are as many passes as there are digits in the longest number set passes [expr {int(log(maxabs($lst))/log($base) + 1)}] # For each pass... for {set pass 0} {$pass < $passes} {incr pass} { # Split by radix, then merge back into the list set lst [concat {*}[splitByRadix $lst $base $pass]] } return $lst }