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/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
#ooRexx
ooRexx
  stack = .queue~of(123, 234) -- creates a stack with a couple of items stack~push("Abc") -- pushing value = stack~pull -- popping value = stack~peek -- peeking -- the is empty test if stack~isEmpty then say "The stack is empty"  
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)
#Raku
Raku
class Turtle { my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1]; my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.   has @.loc = 0,0; has $.dir = 0; has %.world; has $.maxegg; has $.range-x; has $.range-y;   method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; } method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; }   method lay-egg($egg) { %!world{~@!loc} = $egg; $!maxegg max= $egg; $!range-x minmax= @!loc[0]; $!range-y minmax= @!loc[1]; }   method look($ahead = 1) { my $there = @!loc »+« @dv[$!dir] »*» $ahead; %!world{~$there}; }   method forward($ahead = 1) { my $there = @!loc »+« @dv[$!dir] »*» $ahead; @!loc = @($there); }   method showmap() { my $form = "%{$!maxegg.chars}s"; my $endx = $!range-x.max; for $!range-y.list X $!range-x.list -> ($y, $x) { print (%!world{"$x $y"} // '').fmt($form); print $x == $endx ?? "\n" !! ' '; } } }   # Now we can build the spiral in the normal way from outside-in like this:   sub MAIN(Int $size = 5) { my $t = Turtle.new(dir => 2); my $counter = 0; $t.forward(-1); for 0..^ $size -> $ { $t.forward; $t.lay-egg($counter++); } for $size-1 ... 1 -> $run { $t.turn-right; $t.forward, $t.lay-egg($counter++) for 0..^$run; $t.turn-right; $t.forward, $t.lay-egg($counter++) for 0..^$run; } $t.showmap; }
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.
#EasyLang
EasyLang
data[] = [ 29 4 72 44 55 26 27 77 92 5 ] # func qsort left right . . while left < right swap data[(left + right) / 2] data[left] mid = left for i = left + 1 to right if data[i] < data[left] mid += 1 swap data[i] data[mid] . . swap data[left] data[mid] call qsort left mid - 1 left = mid + 1 . . # call qsort 0 len data[] - 1 print data[]
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
#Ruby
Ruby
class Array def patience_sort piles = [] each do |i| if (idx = piles.index{|pile| pile.last <= i}) piles[idx] << i else piles << [i] #create a new pile end end # merge piles result = [] until piles.empty? first = piles.map(&:first) idx = first.index(first.min) result << piles[idx].shift piles.delete_at(idx) if piles[idx].empty? end result end end   a = [4, 65, 2, -31, 0, 99, 83, 782, 1] p a.patience_sort
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.
#Delphi
Delphi
program TestInsertionSort;   {$APPTYPE CONSOLE}   {.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array   type TItem = Integer; // declare ordinal type for array item {$IFDEF DYNARRAY} TArray = array of TItem; // dynamic array {$ELSE} TArray = array[0..15] of TItem; // static array {$ENDIF}   procedure InsertionSort(var A: TArray); var I, J: Integer; Item: TItem;   begin for I:= 1 + Low(A) to High(A) do begin Item:= A[I]; J:= I - 1; while (J >= Low(A)) and (A[J] > Item) do begin A[J + 1]:= A[J]; Dec(J); end; A[J + 1]:= Item; end; end;   var A: TArray; I: Integer;   begin {$IFDEF DYNARRAY} SetLength(A, 16); {$ENDIF} for I:= Low(A) to High(A) do A[I]:= Random(100); for I:= Low(A) to High(A) do Write(A[I]:3); Writeln; InsertionSort(A); for I:= Low(A) to High(A) do Write(A[I]:3); Writeln; Readln; 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.
#D
D
import std.stdio, std.container;   void heapSort(T)(T[] data) /*pure nothrow @safe @nogc*/ { for (auto h = data.heapify; !h.empty; h.removeFront) {} }   void main() { auto items = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]; items.heapSort; items.writeln; }
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.
#Clojure
Clojure
  (defn merge [left right] (cond (nil? left) right (nil? right) left :else (let [[l & *left] left [r & *right] right] (if (<= l r) (cons l (merge *left right)) (cons r (merge left *right))))))   (defn merge-sort [list] (if (< (count list) 2) list (let [[left right] (split-at (/ (count list) 2) list)] (merge (merge-sort left) (merge-sort right)))))  
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.
#PureBasic
PureBasic
If OpenConsole() Define i, j, k, Loops Dim Pile(9) ;-------------------------------------------------------------- ;- Create a Random Pile() For i=1 To 9 ;- Initiate the Pile Pile(i)=i Next For i=9 To 1 Step -1 ;- Do a Fisher-Yates shuffle Swap Pile(i),Pile(Random(i-1)+1) Next Print("Random Pile()  :") For i=1 To 9 Print(" "+Str(Pile(i))) Next ;-------------------------------------------------------------- ;- Start Sorting For i=9 To 2 Step -1 If Pile(i)<>i ;- Only Flip it if the current cake need Swapping Loops+1 j=0 Repeat ;- find place of Pancake(i) in the Pile() j+1 Until Pile(j)=i   For k=1 To (j/2) ;- Flip it up Swap Pile(k),Pile(j-k+1) Next For k=1 To i/2 ;- Flip in place Swap Pile(k),Pile(i-k+1) Next   EndIf Next   Print(#CRLF$+"Resulting Pile() :") For i=1 To 9 Print(" "+str(Pile(i))) Next Print(#CRLF$+"All done in "+str(Loops)+" loops.") Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input() CloseConsole() EndIf
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
#XPL0
XPL0
code ChOut=8, IntOut=11; \intrinsic routines   proc StoogeSort(L, I, J); \Sort array L int L, I, J; int T; [if L(J) < L(I) then [T:= L(I); L(I):= L(J); L(J):= T]; \swap 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); ]; ];   int A, I; [A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; StoogeSort(A, 0, 10-1); for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; ]
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
#Yorick
Yorick
func stoogesort(&L, i, j) { if(is_void(i)) i = 1; if(is_void(j)) j = numberof(L); if(L(j) < L(i)) L([i,j]) = L([j,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; } }
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].
#MAXScript
MAXScript
fn selectionSort arr = ( local min = undefined for i in 1 to arr.count do ( min = i for j in i+1 to arr.count do ( if arr[j] < arr[min] then ( min = j ) ) swap arr[i] arr[min] ) arr )   data = selectionSort #(4, 9, 3, -2, 0, 7, -5, 1, 6, 8) print data
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement. References   Rosetta Code:   O     (complexity).   Wikipedia:   Selection sort.   Wikipedia:   [Big O notation].
#N.2Ft.2Froff
N/t/roff
.de end .. .de array . nr \\$1.c 0 1 . de \\$1.push end . nr \\$1..\\\\n+[\\$1.c] \\\\$1 . end . de \\$1.pushln end . if \\\\n(.$>0 .\\$1.push \\\\$1 . if \\\\n(.$>1 \{ \ . shift . \\$1.pushln \\\\$@ . \} . end . de \\$1.dump end . nr i 0 1 . while \\\\n+i<=\\\\n[\\$1.c] .tm \\\\n[\\$1..\\\\ni] . rr i . end . de \\$1.swap end . if (\\\\$1<=\\\\n[\\$1.c])&(\\\\$2<=\\\\n[\\$1.c]) \{ \ . nr b \\\\n[\\$1..\\\\$1] . nr \\$1..\\\\$1 \\\\n[\\$1..\\\\$2] . nr \\$1..\\\\$2 \\\\nb . rr b . \} . end .. .array myArray .myArray.pushln 14 62 483 21 12 11 0 589 212 10 5 4 95 4 2 2 12 0 0 .de sort . nr i 0 1 . while \\n+i<=\\n[\\$1.c] \{ \ . nr j \\ni 1 . nr st \\nj . while \\n+j<=\\n[\\$1.c] \{ \ . if \\n[\\$1..\\nj]<\\n[\\$1..\\n(st] .nr st \\nj . \} . if !\\n(st=\\ni .\\$1.swap \\ni \\n(st . \} .. .sort myArray .myArray.dump
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.
#Perl
Perl
use Text::Soundex; print soundex("Soundex"), "\n"; # S532 print soundex("Example"), "\n"; # E251 print soundex("Sownteks"), "\n"; # S532 print soundex("Ekzampul"), "\n"; # E251
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#Seed7
Seed7
const proc: shellSort (inout array elemType: arr) is func local var integer: i is 0; var integer: j is 0; var integer: increment is 0; var elemType: help is elemType.value; begin increment := length(arr) div 2; while increment > 0 do for i range 1 to length(arr) do j := i; help := arr[i]; while j > increment and arr[j - increment] > help do arr[j] := arr[j - increment]; j -:= increment; end while; arr[j] := help; end for; increment := increment div 2; end while; end func;
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.
#Sidef
Sidef
func shell_sort(a) { var h = a.len; while (h >>= 1) { for i in (h .. a.end) { var k = a[i]; for (var j = i; (j >= h) && (k < a[j - h]); j -= h) { a[j] = a[j - h]; } a[j] = k; } } return a; }   var a = 10.of {100.irand}; say 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
#OxygenBasic
OxygenBasic
  function f() sys a=1,b=2,c=3,d=4 push a push b push c push d print a "," b "," c "," d 'result 1,2,3,4 a=10 b=20 c=30 d=40 print a "," b "," c "," d 'result 10,20,30,40 pop a pop b pop c pop d print a "," b "," c "," d 'result 4,3,2,1 end function   f  
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)
#REXX
REXX
/*REXX program displays a spiral in a square array (of any size) starting at START. */ parse arg size start . /*obtain optional arguments from the CL*/ if size =='' | size =="," then size =5 /*Not specified? Then use the default.*/ if start=='' | start=="," then start=0 /*Not specified? Then use the default.*/ tot=size**2; L=length(tot + start) /*total number of elements in spiral. */ k=size /*K: is the counter for the spiral. */ row=1; col=0 /*start spiral at row 1, column 0. */ /* [↓] construct the numbered spiral. */ do n=0 for k; col=col + 1; @.col.row=n + start; end; if k==0 then exit /* [↑] build the first row of spiral. */ do until n>=tot /*spiral matrix.*/ do one=1 to -1 by -2 until n>=tot; k=k-1 /*perform twice.*/ do n=n for k; row=row + one; @.col.row=n + start; end /*for the row···*/ do n=n for k; col=col - one; @.col.row=n + start; end /* " " col···*/ end /*one*/ /* ↑↓ direction.*/ end /*until n≥tot*/ /* [↑] done with the matrix spiral. */ /* [↓] display spiral to the screen. */ do r=1 for size; _= right(@.1.r, L) /*construct display row by row. */ do c=2 for size -1; _=_ right(@.c.r, L) /*construct a line for the display. */ end /*col*/ /* [↑] line has an extra leading blank*/ say _ /*display a line (row) of the spiral. */ end /*row*/ /*stick a fork in it, we're all done. */
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.
#EchoLisp
EchoLisp
  (lib 'list) ;; list-partition   (define compare 0) ;; counter   (define (quicksort L compare-predicate: proc aux: (part null)) (if (<= (length L) 1) L (begin ;; counting the number of comparisons (set! compare (+ compare (length (rest L)))) ;; pivot = first element of list (set! part (list-partition (rest L) proc (first L))) (append (quicksort (first part) proc ) (list (first L)) (quicksort (second part) proc)))))  
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
#Scala
Scala
import scala.collection.mutable   object PatienceSort extends App { def sort[A](source: Iterable[A])(implicit bound: A => Ordered[A]): Iterable[A] = { val piles = mutable.ListBuffer[mutable.Stack[A]]()   def PileOrdering: Ordering[mutable.Stack[A]] = (a: mutable.Stack[A], b: mutable.Stack[A]) => b.head.compare(a.head)   // Use a priority queue, to simplify extracting minimum elements. val pq = new mutable.PriorityQueue[mutable.Stack[A]]()(PileOrdering)   // Create ordered piles of elements for (elem <- source) { // Find leftmost "possible" pile // If there isn't a pile available, add a new one. piles.find(p => p.head >= elem) match { case Some(p) => p.push(elem) case _ => piles += mutable.Stack(elem) } }   pq ++= piles   // Return a new list, by taking the smallest stack head // until all stacks are empty. for (_ <- source) yield { val smallestList = pq.dequeue val smallestVal = smallestList.pop   if (smallestList.nonEmpty) pq.enqueue(smallestList) smallestVal } }   println(sort(List(4, 65, 2, -31, 0, 99, 83, 782, 1))) }
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Insertion sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#E
E
def insertionSort(array) { for i in 1..!(array.size()) { def value := array[i] var j := i-1 while (j >= 0 && array[j] > value) { array[j + 1] := array[j] j -= 1 } array[j+1] := value } }
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.
#Dart
Dart
  void heapSort(List a) { int count = a.length;   // first place 'a' in max-heap order heapify(a, count);   int end = count - 1; while (end > 0) { // swap the root (maximum value) of the heap with the // last element of the heap int tmp = a[end]; a[end] = a[0]; a[0] = tmp;   // put the heap back in max-heap order siftDown(a, 0, end - 1);   // decrement the size of the heap so that the previous // max value will stay in its proper place end--; } }       void heapify(List a, int count) { // start is assigned the index in 'a' of the last parent node int start = ((count - 2)/2).toInt(); // binary heap   while (start >= 0) { // 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--; } }   void siftDown(List a, int start, int end) { // end represents the limit of how far down the heap to shift int root = start;   while ((root*2 + 1) <= end) { // While the root has at least one child int 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 && a[child] < a[child + 1]) { child = child+1; // .. then point to the right child instead }   if (a[root] < a[child]) { // out of max-heap order int tmp = a[root]; a[root] = a[child]; a[child] = tmp; root = child; // repeat to continue shifting down the child now } else { return; } }   }   void main() { var arr=[1,5,2,7,3,9,4,6,8]; print("Before sort"); arr.forEach((var i)=>print("$i")); heapSort(arr); print("After sort"); arr.forEach((var i)=>print("$i")); }    
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.
#Delphi
Delphi
proc nonrec siftDown([*] int a; word start, end) void: word root, child; int temp; bool stop;   root := start; stop := false; while not stop and root*2 + 1 <= end do child := root*2 + 1; if child+1 <= end and a[child] < a[child + 1] then child := child + 1 fi; if a[root] < a[child] then temp := a[root]; a[root] := a[child]; a[child] := temp; root := child else stop := true fi od corp   proc nonrec heapify([*] int a; word count) void: word start; bool stop;   start := (count - 2) / 2; stop := false; while not stop do siftDown(a, start, count-1); if start=0 then stop := true /* avoid having to use a signed index */ else start := start - 1 fi od corp   proc nonrec heapsort([*] int a) void: word end; int temp;   heapify(a, dim(a,1)); end := dim(a,1) - 1; while end > 0 do temp := a[0]; a[0] := a[end]; a[end] := temp; end := end - 1; siftDown(a, 0, end) od corp   /* Test */ proc nonrec main() void: int i; [10] int a = (9, -5, 3, 3, 24, -16, 3, -120, 250, 17);   write("Before sorting: "); for i from 0 upto 9 do write(a[i]:5) od; writeln();   heapsort(a); write("After sorting: "); for i from 0 upto 9 do write(a[i]:5) od corp
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. MERGESORT. AUTHOR. DAVE STRATFORD. DATE-WRITTEN. APRIL 2010. INSTALLATION. HEXAGON SYSTEMS LIMITED. ****************************************************************** * MERGE SORT * * The Merge sort uses a completely different paradigm, one of * * divide and conquer, to many of the other sorts. The data set * * is split into smaller sub sets upon which are sorted and then * * merged together to form the final sorted data set. * * This version uses the recursive method. Split the data set in * * half and perform a merge sort on each half. This in turn splits* * each half again and again until each set is just one or 2 items* * long. A set of one item is already sorted so is ignored, a set * * of two is compared and swapped as necessary. The smaller data * * sets are then repeatedly merged together to eventually form the* * full, sorted, set. * * Since cobol cannot do recursion this module only simulates it * * so is not as fast as a normal recursive version would be. * * Scales very well to larger data sets, its relative complexity * * means it is not suited to sorting smaller data sets: use an * * Insertion sort instead as the Merge sort is a stable sort. * ******************************************************************   ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. ICL VME. OBJECT-COMPUTER. ICL VME.   INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT FA-INPUT-FILE ASSIGN FL01. SELECT FB-OUTPUT-FILE ASSIGN FL02.   DATA DIVISION. FILE SECTION. FD FA-INPUT-FILE. 01 FA-INPUT-REC. 03 FA-DATA PIC 9(6).   FD FB-OUTPUT-FILE. 01 FB-OUTPUT-REC PIC 9(6).   WORKING-STORAGE SECTION. 01 WA-IDENTITY. 03 WA-PROGNAME PIC X(10) VALUE "MERGESORT". 03 WA-VERSION PIC X(6) VALUE "000001".   01 WB-TABLE. 03 WB-ENTRY PIC 9(8) COMP SYNC OCCURS 100000 INDEXED BY WB-IX-1 WB-IX-2.   01 WC-VARS. 03 WC-SIZE PIC S9(8) COMP SYNC. 03 WC-TEMP PIC S9(8) COMP SYNC. 03 WC-START PIC S9(8) COMP SYNC. 03 WC-MIDDLE PIC S9(8) COMP SYNC. 03 WC-END PIC S9(8) COMP SYNC.   01 WD-FIRST-HALF. 03 WD-FH-MAX PIC S9(8) COMP SYNC. 03 WD-ENTRY PIC 9(8) COMP SYNC OCCURS 50000 INDEXED BY WD-IX.   01 WF-CONDITION-FLAGS. 03 WF-EOF-FLAG PIC X. 88 END-OF-FILE VALUE "Y". 03 WF-EMPTY-FILE-FLAG PIC X. 88 EMPTY-FILE VALUE "Y".   01 WS-STACK. * This stack is big enough to sort a list of 1million items. 03 WS-STACK-ENTRY OCCURS 20 INDEXED BY WS-STACK-TOP. 05 WS-START PIC S9(8) COMP SYNC. 05 WS-MIDDLE PIC S9(8) COMP SYNC. 05 WS-END PIC S9(8) COMP SYNC. 05 WS-FS-FLAG PIC X. 88 FIRST-HALF VALUE "F". 88 SECOND-HALF VALUE "S". 88 WS-ALL VALUE "A". 05 WS-IO-FLAG PIC X. 88 WS-IN VALUE "I". 88 WS-OUT VALUE "O".   PROCEDURE DIVISION. A-MAIN SECTION. A-000. PERFORM B-INITIALISE.   IF NOT EMPTY-FILE PERFORM C-PROCESS.   PERFORM D-FINISH.   A-999. STOP RUN.   B-INITIALISE SECTION. B-000. DISPLAY "*** " WA-PROGNAME " VERSION " WA-VERSION " STARTING ***".   MOVE ALL "N" TO WF-CONDITION-FLAGS. OPEN INPUT FA-INPUT-FILE. SET WB-IX-1 TO 0.   READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG WF-EMPTY-FILE-FLAG.   PERFORM BA-READ-INPUT UNTIL END-OF-FILE.   CLOSE FA-INPUT-FILE.   SET WC-SIZE TO WB-IX-1.   B-999. EXIT.   BA-READ-INPUT SECTION. BA-000. SET WB-IX-1 UP BY 1. MOVE FA-DATA TO WB-ENTRY(WB-IX-1).   READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG.   BA-999. EXIT.   C-PROCESS SECTION. C-000. DISPLAY "SORT STARTING".   MOVE 1 TO WS-START(1). MOVE WC-SIZE TO WS-END(1). MOVE "F" TO WS-FS-FLAG(1). MOVE "I" TO WS-IO-FLAG(1). SET WS-STACK-TOP TO 2.   PERFORM E-MERGE-SORT UNTIL WS-OUT(1).   DISPLAY "SORT FINISHED".   C-999. EXIT.   D-FINISH SECTION. D-000. OPEN OUTPUT FB-OUTPUT-FILE. SET WB-IX-1 TO 1.   PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE.   CLOSE FB-OUTPUT-FILE.   DISPLAY "*** " WA-PROGNAME " FINISHED ***".   D-999. EXIT.   DA-WRITE-OUTPUT SECTION. DA-000. WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1). SET WB-IX-1 UP BY 1.   DA-999. EXIT.   ****************************************************************** E-MERGE-SORT SECTION. *===================== * * This section controls the simulated recursion. * ****************************************************************** E-000. IF WS-OUT(WS-STACK-TOP - 1) GO TO E-010.   MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. MOVE WS-END(WS-STACK-TOP - 1) TO WC-END.   * First check size of part we are dealing with. IF WC-END - WC-START = 0 * Only 1 number in range, so simply set for output, and move on MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1) GO TO E-010.   IF WC-END - WC-START = 1 * 2 numbers, so compare and swap as necessary. Set for output MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1) IF WB-ENTRY(WC-START) > WB-ENTRY(WC-END) MOVE WB-ENTRY(WC-START) TO WC-TEMP MOVE WB-ENTRY(WC-END) TO WB-ENTRY(WC-START) MOVE WC-TEMP TO WB-ENTRY(WC-END) GO TO E-010 ELSE GO TO E-010.   * More than 2, so split and carry on down COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2.   MOVE WC-START TO WS-START(WS-STACK-TOP). MOVE WC-MIDDLE TO WS-END(WS-STACK-TOP). MOVE "F" TO WS-FS-FLAG(WS-STACK-TOP). MOVE "I" TO WS-IO-FLAG(WS-STACK-TOP). SET WS-STACK-TOP UP BY 1.   GO TO E-999.   E-010. SET WS-STACK-TOP DOWN BY 1.   IF SECOND-HALF(WS-STACK-TOP) GO TO E-020.   MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2 + 1.   MOVE WC-MIDDLE TO WS-START(WS-STACK-TOP). MOVE WC-END TO WS-END(WS-STACK-TOP). MOVE "S" TO WS-FS-FLAG(WS-STACK-TOP). MOVE "I" TO WS-IO-FLAG(WS-STACK-TOP). SET WS-STACK-TOP UP BY 1.   GO TO E-999.   E-020. MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2. PERFORM H-PROCESS-MERGE. MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1).   E-999. EXIT.   ****************************************************************** H-PROCESS-MERGE SECTION. *======================== * * This section identifies which data is to be merged, and then * * merges the two data streams into a single larger data stream. * ****************************************************************** H-000. INITIALISE WD-FIRST-HALF. COMPUTE WD-FH-MAX = WC-MIDDLE - WC-START + 1. SET WD-IX TO 1.   PERFORM HA-COPY-OUT VARYING WB-IX-1 FROM WC-START BY 1 UNTIL WB-IX-1 > WC-MIDDLE.   SET WB-IX-1 TO WC-START. SET WB-IX-2 TO WC-MIDDLE. SET WB-IX-2 UP BY 1. SET WD-IX TO 1.   PERFORM HB-MERGE UNTIL WD-IX > WD-FH-MAX OR WB-IX-2 > WC-END.   PERFORM HC-COPY-BACK UNTIL WD-IX > WD-FH-MAX.   H-999. EXIT.   HA-COPY-OUT SECTION. HA-000. MOVE WB-ENTRY(WB-IX-1) TO WD-ENTRY(WD-IX). SET WD-IX UP BY 1.   HA-999. EXIT.   HB-MERGE SECTION. HB-000. IF WB-ENTRY(WB-IX-2) < WD-ENTRY(WD-IX) MOVE WB-ENTRY(WB-IX-2) TO WB-ENTRY(WB-IX-1) SET WB-IX-2 UP BY 1 ELSE MOVE WD-ENTRY(WD-IX) TO WB-ENTRY(WB-IX-1) SET WD-IX UP BY 1.   SET WB-IX-1 UP BY 1.   HB-999. EXIT.   HC-COPY-BACK SECTION. HC-000. MOVE WD-ENTRY(WD-IX) TO WB-ENTRY(WB-IX-1). SET WD-IX UP BY 1. SET WB-IX-1 UP BY 1.   HC-999. EXIT.
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.
#Python
Python
tutor = False   def pancakesort(data): if len(data) <= 1: return data if tutor: print() for size in range(len(data), 1, -1): maxindex = max(range(size), key=data.__getitem__) if maxindex+1 != size: # This indexed max needs moving if maxindex != 0: # Flip the max item to the left if tutor: print('With: %r doflip  %i'  % ( ' '.join(str(x) for x in data), maxindex+1 )) data[:maxindex+1] = reversed(data[:maxindex+1]) # Flip it into its final position if tutor: print('With: %r doflip %i'  % ( ' '.join(str(x) for x in data), size )) data[:size] = reversed(data[:size]) if tutor: print()
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
#zkl
zkl
fcn stoogeSort(list,i=0,j=Void){ if(Void==j) j=list.len() - 1; // default parameters set before call if(list[j]<list[i]) list.swap(i,j); if(j - i >1){ t:=(j - i + 1)/3; stoogeSort(list,i , j-t); stoogeSort(list,i+t, j ); stoogeSort(list,i , j-t); } list }
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].
#Nanoquery
Nanoquery
import math   def sort(nums) global math for currentPlace in range(0, len(nums) - 2) smallest = math.maxint smallestAt = currentPlace + 1 for check in range(currentPlace, len(nums) - 1) if nums[check] < smallest smallestAt = check smallest = nums[check] end end temp = nums[currentPlace] nums[currentPlace] = nums[smallestAt] nums[smallestAt] = temp end return nums end
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].
#Nemerle
Nemerle
using System; using System.Console;   module Selection { public static Sort[T](this a : array[T]) : void where T : IComparable { mutable k = 0; def lastindex = a.Length - 1;   foreach (i in [0 .. lastindex]) { k = i; foreach (j in [i .. lastindex]) when (a[j].CompareTo(a[k]) < 0) k = j; a[i] <-> a[k]; } }   Main() : void { def arr = array[6, 2, 8, 3, 9, 4, 7, 3, 9, 1]; arr.Sort(); foreach (i in arr) Write($"$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.
#Phix
Phix
with javascript_semantics constant soundex_alphabet = "0123012#02245501262301#202" -- ABCDEFGHIJKLMNOPQRSTUVWXYZ function soundex(string name) string res = "0000" integer rdx = 1, ch, curr, prev for i=1 to length(name) do ch = upper(name[i]) if ch>='A' and ch<='Z' then curr = soundex_alphabet[ch-'A'+1] if rdx=1 then res[1] = ch rdx = 2 prev = curr elsif curr!='#' then if curr!='0' and curr!=prev then res[rdx] = curr if rdx=4 then exit end if rdx += 1 end if prev = curr end if end if end for return res end function constant tests = { {"Ashcraft", "A261"}, -- not "A226" {"Ashcroft", "A261"}, -- not "A226" {"Ashkrofd", "A261"}, -- not "A226" {"Burroughs", "B620"}, {"Burrows", "B620"}, {"ciondecks", "C532"}, {"Example", "E251"}, {"Ekzampul", "E251"}, {"Ellery", "E460"}, {"Euler", "E460"}, {"Gauss", "G200"}, {"Ghosh", "G200"}, {"Gutierrez", "G362"}, {"He", "H000"}, {"Heilbronn", "H416"}, {"Hilbert", "H416"}, {"Honeyman", "H555"}, -- not "H500" {"Jackson", "J250"}, {"Kant", "K530"}, {"Knuth", "K530"}, {"Lee", "L000"}, {"Ladd", "L300"}, {"Lloyd", "L300"}, {"Lissajous", "L222"}, {"Lukasiewicz", "L222"}, {"Moses", "M220"}, {"O'Hara", "O600"}, {"Pfister", "P236"}, -- not "P123" {"Robert", "R163"}, {"Rupert", "R163"}, {"Rubin", "R150"}, {"r~@sum~@", "R250"}, {"Soundex", "S532"}, {"Sownteks", "S532"}, {"Tymczak", "T522"}, -- not "T520" {"VanDeusen", "V532"}, {"Washington", "W252"}, {"Wheaton", "W350"}, {"Weeton", "W350"}, {"", "0000"}, {" ", "0000"}, {"12346", "0000"}, {"aaa a", "A000"} } for i=1 to length(tests) do string {name,expected} = tests[i], res = soundex(name), ok = iff(res=expected?"":"*** ERROR ***") printf(1,"%-12s -> %s %s\n",{name,res,ok}) end for
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.
#Swift
Swift
func shellsort<T where T : Comparable>(inout seq: [T]) { var inc = seq.count / 2 while inc > 0 { for (var i, el) in EnumerateSequence(seq) { while i >= inc && seq[i - inc] > el { seq[i] = seq[i - inc] i -= inc } seq[i] = el } if inc == 2 { inc = 1 } else { inc = inc * 5 / 11 } } }
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.
#Tcl
Tcl
package require Tcl 8.5   proc shellsort {m} { set len [llength $m] set inc [expr {$len / 2}] while {$inc > 0} { for {set i $inc} {$i < $len} {incr i} { set j $i set temp [lindex $m $i] while {$j >= $inc && [set val [lindex $m [expr {$j - $inc}]]] > $temp} { lset m $j $val incr j -$inc } lset m $j $temp } set inc [expr {$inc == 2 ? 1 : $inc * 5 / 11}] } return $m }   puts [shellsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9
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
#Oz
Oz
functor export New Push Pop Empty define fun {New} {NewCell nil} end   proc {Push Stack Element} NewStack %% Use atomic swap for thread safety OldStack = Stack := NewStack in NewStack = Element|OldStack end   proc {Pop Stack ?Result} NewStack %% Use atomic swap for thread safety OldStack = Stack := NewStack in Result|NewStack = OldStack end   fun {Empty Stack} @Stack == nil 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)
#Ring
Ring
  # Project : Spiral matrix   load "guilib.ring" load "stdlib.ring" new qapp { win1 = new qwidget() { setwindowtitle("Spiral matrix") setgeometry(100,100,600,400) n = 5 result = newlist(n,n) spiral = newlist(n,n) k = 1 top = 1 bottom = n left = 1 right = n while (k <= n*n) for i= left to right result[top][i] = k k = k + 1 next top = top + 1 for i = top to bottom result[i][right] = k k = k + 1 next right = right - 1 for i = right to left step -1 result[bottom][i] = k k = k + 1 next bottom = bottom - 1 for i = bottom to top step -1 result[i][left] = k k = k + 1 next left = left + 1 end for m = 1 to n for p = 1 to n spiral[p][m] = new qpushbutton(win1) { x = 150+m*40 y = 30 + p*40 setgeometry(x,y,40,40) settext(string(result[m][p])) } next next show() } exec() }  
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.
#Eero
Eero
#import <Foundation/Foundation.h>   void quicksortInPlace(MutableArray array, const long first, const long last) if first >= last return Value pivot = array[(first + last) / 2] left := first right := last while left <= right while array[left] < pivot left++ while array[right] > pivot right-- if left <= right array.exchangeObjectAtIndex: left++, withObjectAtIndex: right--   quicksortInPlace(array, first, right) quicksortInPlace(array, left, last)   Array quicksort(Array unsorted) a := [] a.addObjectsFromArray: unsorted quicksortInPlace(a, 0, a.count - 1) return a     int main(int argc, const char * argv[]) autoreleasepool a := [1, 3, 5, 7, 9, 8, 6, 4, 2] Log( 'Unsorted: %@', a) Log( 'Sorted: %@', quicksort(a) ) b := ['Emil', 'Peg', 'Helen', 'Juergen', 'David', 'Rick', 'Barb', 'Mike', 'Tom'] Log( 'Unsorted: %@', b) Log( 'Sorted: %@', quicksort(b) )   return 0
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
#Scheme
Scheme
(define-library (rosetta-code k-way-merge)   (export k-way-merge)   (import (scheme base)) (import (scheme case-lambda)) (import (only (srfi 1) car+cdr)) (import (only (srfi 1) reverse!)) (import (only (srfi 132) list-merge)) (import (only (srfi 151) bitwise-xor))   (begin   ;; ;; The algorithm employed here is "tournament tree" as in the ;; following article, which is based on Knuth, volume 3. ;; ;; 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 a Scheme vector, and one can find an ;; opponent quickly by simply toggling the least significant bit ;; of a competitor's array index. ;;   (define // truncate-quotient)   (define-record-type <infinity> (make-infinity) infinity?)   (define infinity (make-infinity))   (define (next-power-of-two n) ;; This need not be a fast implementation. It can assume n >= 3, ;; because one can use an ordinary 2-way merge for n = 2. (let loop ((pow2 4)) (if (<= n pow2) pow2 (loop (+ pow2 pow2)))))   (define (play-game <? x y) (cond ((infinity? x) #f) ((infinity? y) #t) (else (not (<? y x)))))   (define (build-tree <? heads) ;; We do not use vector indices of zero. Thus our indexing is ;; 1-based. (let* ((total-external-nodes (next-power-of-two (vector-length heads))) (total-nodes (- (* 2 total-external-nodes) 1)) (winners (make-vector (+ total-nodes 1)))) (do ((i 0 (+ i 1))) ((= i total-external-nodes)) (let ((j (+ total-external-nodes i))) (if (< i (vector-length heads)) (let ((entry (cons (vector-ref heads i) i))) (vector-set! winners j entry)) (let ((entry (cons infinity i))) (vector-set! winners j entry))))) (let loop ((istart total-external-nodes)) (do ((i istart (+ i 2))) ((= i (+ istart istart))) (let* ((i1 i) (i2 (bitwise-xor i 1)) (elem1 (car (vector-ref winners i1))) (elem2 (car (vector-ref winners i2))) (wins1? (play-game <? elem1 elem2)) (iwinner (if wins1? i1 i2)) (winner (vector-ref winners iwinner)) (iparent (// i 2))) (vector-set! winners iparent winner))) (if (= istart 2) winners (loop (// istart 2))))))   (define (replay-games <? winners i) (let loop ((i i)) (unless (= i 1) (let* ((i1 i) (i2 (bitwise-xor i 1)) (elem1 (car (vector-ref winners i1))) (elem2 (car (vector-ref winners i2))) (wins1? (play-game <? elem1 elem2)) (iwinner (if wins1? i1 i2)) (winner (vector-ref winners iwinner)) (iparent (// i 2))) (vector-set! winners iparent winner) (loop iparent)))))   (define (get-next lst) (if (null? lst) (values infinity lst) ; End of list. Return a sentinel. (car+cdr lst)))   (define (merge-lists <? lists) (let* ((heads (list->vector (map car lists))) (tails (list->vector (map cdr lists)))) (let ((winners (build-tree <? heads))) (let loop ((outputs '())) (let-values (((winner-value winner-index) (car+cdr (vector-ref winners 1)))) (if (infinity? winner-value) (reverse! outputs) (let-values (((hd tl) (get-next (vector-ref tails winner-index)))) (vector-set! tails winner-index tl) (let ((entry (cons hd winner-index)) (i (+ (// (vector-length winners) 2) winner-index))) (vector-set! winners i entry) (replay-games <? winners i) (loop (cons winner-value outputs))))))))))   (define k-way-merge (case-lambda ((<? lst1) lst1) ((<? lst1 lst2) (list-merge <? lst1 lst2)) ((<? . lists) (merge-lists <? lists))))   )) ;; library (rosetta-code k-way-merge)   (define-library (rosetta-code patience-sort)   (export patience-sort)   (import (scheme base)) (import (rosetta-code k-way-merge))   (begin   (define (find-pile <? x num-piles piles) ;; ;; Do a Bottenbruch search for the leftmost pile whose top is ;; greater than or equal to x. The search starts at 0 and ends ;; at (- num-piles 1). 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 ;; (let loop ((j 0) (k (- num-piles 1))) (if (= j k) (if (or (not (= j (- num-piles 1))) (not (<? (car (vector-ref piles j)) x))) j ; x fits onto one of the piles. (+ j 1)) ; x needs a new pile. (let ((i (floor-quotient (+ j k) 2))) (if (<? (car (vector-ref piles i)) x) ;; x is greater than the element at i. (loop (+ i 1) k) (loop j i))))))   (define (resize-table table-size num-piles piles) ;; If necessary, allocate a new table of larger size. (if (not (= num-piles table-size)) (values table-size piles) (let* ((new-size (* table-size 2)) (new-piles (make-vector new-size))) (vector-copy! new-piles 0 piles) (values new-size new-piles))))   (define initial-table-size 64)   (define (deal <? lst) (let loop ((lst lst) (table-size initial-table-size) (num-piles 0) (piles (make-vector initial-table-size))) (cond ((null? lst) (values num-piles piles)) ((zero? num-piles) (vector-set! piles 0 (list (car lst))) (loop (cdr lst) table-size 1 piles)) (else (let* ((x (car lst)) (i (find-pile <? x num-piles piles))) (if (= i num-piles) (let-values (((table-size piles) (resize-table table-size num-piles piles))) ;; Start a new pile at the far right. (vector-set! piles num-piles (list x)) (loop (cdr lst) table-size (+ num-piles 1) piles)) (begin (vector-set! piles i (cons x (vector-ref piles i))) (loop (cdr lst) table-size num-piles piles))))))))   (define (patience-sort <? lst) (let-values (((num-piles piles) (deal <? lst))) (apply k-way-merge (cons <? (vector->list piles 0 num-piles)))))   )) ;; library (rosetta-code patience-sort)   ;;-------------------------------------------------------------------- ;; ;; A little demonstration. ;;   (import (scheme base)) (import (scheme write)) (import (rosetta-code patience-sort))   (define example-numbers '(22 15 98 82 22 4 58 70 80 38 49 48 46 54 93 8 54 2 72 84 86 76 53 37 90)) (display "unsorted ") (write example-numbers) (newline) (display "sorted ") (write (patience-sort < example-numbers)) (newline)   ;;--------------------------------------------------------------------
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.
#EasyLang
EasyLang
subr sort for i = 1 to len data[] - 1 h = data[i] j = i - 1 while j >= 0 and h < data[j] data[j + 1] = data[j] j -= 1 . data[j + 1] = h . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] call sort print data[]
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.
#Draco
Draco
proc nonrec siftDown([*] int a; word start, end) void: word root, child; int temp; bool stop;   root := start; stop := false; while not stop and root*2 + 1 <= end do child := root*2 + 1; if child+1 <= end and a[child] < a[child + 1] then child := child + 1 fi; if a[root] < a[child] then temp := a[root]; a[root] := a[child]; a[child] := temp; root := child else stop := true fi od corp   proc nonrec heapify([*] int a; word count) void: word start; bool stop;   start := (count - 2) / 2; stop := false; while not stop do siftDown(a, start, count-1); if start=0 then stop := true /* avoid having to use a signed index */ else start := start - 1 fi od corp   proc nonrec heapsort([*] int a) void: word end; int temp;   heapify(a, dim(a,1)); end := dim(a,1) - 1; while end > 0 do temp := a[0]; a[0] := a[end]; a[end] := temp; end := end - 1; siftDown(a, 0, end) od corp   /* Test */ proc nonrec main() void: int i; [10] int a = (9, -5, 3, 3, 24, -16, 3, -120, 250, 17);   write("Before sorting: "); for i from 0 upto 9 do write(a[i]:5) od; writeln();   heapsort(a); write("After sorting: "); for i from 0 upto 9 do write(a[i]:5) od corp
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.
#CoffeeScript
CoffeeScript
# This is a simple version of mergesort that returns brand-new arrays. # A more sophisticated version would do more in-place optimizations. merge_sort = (arr) -> if arr.length <= 1 return (elem for elem in arr) m = Math.floor(arr.length / 2) arr1 = merge_sort(arr.slice 0, m) arr2 = merge_sort(arr.slice m) result = [] p1 = p2 = 0 while true if p1 >= arr1.length if p2 >= arr2.length return result result.push arr2[p2] p2 += 1 else if p2 >= arr2.length or arr1[p1] < arr2[p2] result.push arr1[p1] p1 += 1 else result.push arr2[p2] p2 += 1   do -> console.log merge_sort [2,4,6,8,1,3,5,7,9,10,11,0,13,12]
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.
#Quackery
Quackery
[ split reverse join ] is flip ( [ n --> [ )   [ 0 swap behead swap witheach [ 2dup > iff [ nip nip i^ 1+ swap ] else drop ] drop ] is smallest ( [ --> n )   [ dup size times [ dup i^ split nip smallest i^ + flip i^ flip ] ] is pancakesort ( [ --> [ )
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.
#Racket
Racket
  #lang racket   (define (pancake-sort l) (define (flip l n) (append (reverse (take l n)) (drop l n))) (for/fold ([l l]) ([i (in-range (length l) 1 -1)]) (let* ([i2 (cdr (for/fold ([m #f]) ([x l] [j i]) (if (and m (<= x (car m))) m (cons x j))))] [l (if (zero? i2) l (flip l (add1 i2)))]) (flip l i))))   (pancake-sort (shuffle (range 0 10))) ;; => '(0 1 2 3 4 5 6 7 8 9)  
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].
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.util.List   placesList = [String - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - ]   lists = [ - placesList - , selectionSort(String[] Arrays.copyOf(placesList, placesList.length)) - ]   loop ln = 0 to lists.length - 1 cl = lists[ln] loop ct = 0 to cl.length - 1 say cl[ct] end ct say end ln   return   method selectionSort(a = String[]) public constant binary returns String[]   rl = String[a.length] al = List selectionSort(Arrays.asList(a)) al.toArray(rl)   return rl   method selectionSort(a = List) public constant binary returns ArrayList   ra = ArrayList(a) n = ra.size   iPos = int iMin = int   loop iPos = 0 to n - 1 iMin = iPos loop i_ = iPos + 1 to n - 1 if (Comparable ra.get(i_)).compareTo(Comparable ra.get(iMin)) < 0 then do iMin = i_ end end i_ if iMin \= iPos then do swap = ra.get(iPos) ra.set(iPos, ra.get(iMin)) ra.set(iMin, swap) end end iPos   return ra  
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.
#PHP
PHP
<?php echo soundex("Soundex"), "\n"; // S532 echo soundex("Example"), "\n"; // E251 echo soundex("Sownteks"), "\n"; // S532 echo soundex("Ekzampul"), "\n"; // E251 ?>
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#uBasic.2F4tH
uBasic/4tH
PRINT "Shell sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Shellsort (n) PROC _ShowArray (n) PRINT   END     _Shellsort PARAM (1) ' Shellsort subroutine LOCAL (4) b@ = a@   DO WHILE b@ b@ = b@ / 2 FOR c@ = b@ TO a@ - 1 e@ = @(c@) d@ = c@ DO WHILE (d@ > b@-1) * (e@ < @(ABS(d@ - b@))) @(d@) = @(d@ - b@) d@ = d@ - b@ LOOP @(d@) = e@ NEXT LOOP RETURN     _Swap PARAM(2) ' Swap two array elements PUSH @(a@) @(a@) = @(b@) @(b@) = POP() RETURN     _InitArray ' Init example array PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1   FOR i = 0 TO 9 @(i) = POP() NEXT   RETURN (i)     _ShowArray PARAM (1) ' Show array subroutine FOR i = 0 TO a@-1 PRINT @(i), NEXT   PRINT 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
#PARI.2FGP
PARI/GP
push(x)=v=concat(v,[x]);; pop()={ if(#v, my(x=v[#v]); v=vecextract(v,1<<(#v-1)-1); x , error("Stack underflow") ) }; empty()=v==[]; peek()={ if(#v, v[#v] , error("Stack underflow") ) };
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)
#Ruby
Ruby
def spiral(n) spiral = Array.new(n) {Array.new(n, nil)} # n x n array of nils runs = n.downto(0).each_cons(2).to_a.flatten # n==5; [5,4,4,3,3,2,2,1,1,0] delta = [[1,0], [0,1], [-1,0], [0,-1]].cycle x, y, value = -1, 0, -1 for run in runs dx, dy = delta.next run.times { spiral[y+=dy][x+=dx] = (value+=1) } end spiral end   def print_matrix(m) width = m.flatten.map{|x| x.to_s.size}.max m.each {|row| puts row.map {|x| "%#{width}s " % x}.join} end   print_matrix spiral(5)
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.
#Eiffel
Eiffel
QUICKSORT
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
#Sidef
Sidef
func patience(deck) { var stacks = []; deck.each { |card| given (stacks.first { card < .last }) { |stack| case (defined stack) { stack << card } default { stacks << [card] } } }   gather { while (stacks) { take stacks.min_by { .last }.pop stacks.grep!{ !.is_empty } } } }   var a = [4, 65, 2, -31, 0, 99, 83, 782, 1] say patience(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.
#Eiffel
Eiffel
class MY_SORTED_SET [G -> COMPARABLE] inherit TWO_WAY_SORTED_SET [G] redefine sort end create make   feature sort -- Insertion sort local l_j: INTEGER l_value: like item do across 2 |..| count as ii loop from l_j := ii.item - 1 l_value := Current.i_th (ii.item) until l_j < 1 or Current.i_th (l_j) <= l_value loop Current.i_th (l_j + 1) := Current.i_th (l_j) l_j := l_j - 1 end Current.i_th (l_j + 1) := l_value end 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.
#E
E
def heapsort := { def cswap(c, a, b) { def t := c[a] c[a] := c[b] c[b] := t # println(c) }   def siftDown(array, start, finish) { var root := start while (var child := root * 2 + 1 child <= finish) { if (child + 1 <= finish && array[child] < array[child + 1]) { child += 1 } if (array[root] < array[child]) { cswap(array, root, child) root := child } else { break } } }   /** Heapsort (in-place). */ def heapsort(array) { # in pseudo-code, heapify only called once, so inline it here for start in (0..((array.size()-2)//2)).descending() { siftDown(array, start, array.size()-1) }   for finish in (0..(array.size()-1)).descending() { cswap(array, 0, finish) siftDown(array, 0, finish - 1) } } }
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.
#Common_Lisp
Common Lisp
(defun merge-sort (result-type sequence predicate) (let ((split (floor (length sequence) 2))) (if (zerop split) (copy-seq sequence) (merge result-type (merge-sort result-type (subseq sequence 0 split) predicate) (merge-sort result-type (subseq sequence split) predicate) predicate))))
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.
#Raku
Raku
sub pancake_sort ( @a is copy ) { my $endpoint = @a.end; while $endpoint > 0 and not [<] @a { my $max_i = [0..$endpoint].max: { @a[$_] }; my $max = @a[$max_i]; if @a[$endpoint] == $max { $endpoint-- while @a[$endpoint] == $max; next; } # @a[$endpoint] is not $max, so it needs flipping; # Flip twice if max is not already at the top. @a[0..$max_i] .= reverse if $max_i != 0; @a[0..$endpoint] .= reverse; $endpoint--; } return @a; } my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4; say 'input = ' ~ @data; say 'output = ' ~ @data.&pancake_sort;  
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].
#Nim
Nim
proc selectionSort[T](a: var openarray[T]) = let n = a.len for i in 0 ..< n: var m = i for j in i ..< n: if a[j] < a[m]: m = j swap a[i], a[m]   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] selectionSort a echo a
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].
#OCaml
OCaml
let rec selection_sort = function [] -> [] | first::lst -> let rec select_r small output = function [] -> small :: selection_sort output | x::xs when x < small -> select_r x (small::output) xs | x::xs -> select_r small (x::output) xs in select_r first [] lst
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.
#Picat
Picat
go => Names = split("Lloyd Woolcock Donnell Baragwanath Williams Ashcroft Ashcraft Euler Ellery Gauss Ghosh Hilbert Heilbronn Knuth Kant Ladd Lukasiewicz Lissajous O'Hara"), SoundexNames = split("L300 W422 D540 B625 W452 A261 A261 E460 E460 G200 G200 H416 H416 K530 K530 L300 L222 L222 O600"),   foreach({Name,Correct} in zip(Names, SoundexNames)) S = soundex(Name), printf("%s: %s ",Name,S), if S == Correct then println("ok") else printf("not correct! Should be: %s\n", Correct) end end, nl.   soundex("", _) = "" => true. soundex(Word) = Soundex => SoundexAlphabet = "0123012#02245501262301#202", Soundex = "", LastC = '?', foreach(Ch in Word.to_uppercase, C = ord(Ch), C >= 0'A', C <= 0'Z', Soundex.len < 4) ThisC := SoundexAlphabet[C-0'A'+1], Skip = false, % to handle '#' if Soundex.len == 0 then Soundex := Soundex ++ [Ch] elseif ThisC == '#' then Skip := true elseif ThisC != '0', ThisC != LastC then Soundex := Soundex ++ [ThisC] end, if Skip == false then LastC := ThisC end end, Soundex := Soundex.padRight(4,'0').   padRight(S,Len,PadChar) = S ++ [PadChar : _ in 1..Len-S.len].
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.
#Visual_Basic
Visual Basic
Sub arrShellSort(ByVal arrData As Variant) Dim lngHold, lngGap As Long Dim lngCount, lngMin, lngMax As Long Dim varItem As Variant ' lngMin = LBound(arrData) lngMax = UBound(arrData) lngGap = lngMin Do While (lngGap < lngMax) lngGap = 3 * lngGap + 1 Loop Do While (lngGap > 1) lngGap = lngGap \ 3 For lngCount = lngGap + lngMin To lngMax varItem = arrData(lngCount) lngHold = lngCount Do While ((arrData(lngHold - lngGap) > varItem)) arrData(lngHold) = arrData(lngHold - lngGap) lngHold = lngHold - lngGap If (lngHold < lngMin + lngGap) Then Exit Do Loop arrData(lngHold) = varItem Next Loop arrShellSort = arrData End Sub'
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
#Pascal
Pascal
{ tStack is the actual stack type, tStackNode a helper type } type pStackNode = ^tStackNode; tStackNode = record next: pStackNode; data: integer; end; tStack = record top: pStackNode; end;   { Always call InitStack before using a stack } procedure InitStack(var stack: tStack); begin stack.top := nil end;   { This function removes all content from a stack; call before disposing, or before a local stack variable goes out of scope } procedure ClearStack(var stack: tStack); var node: pStackNode; begin while stack.top <> nil do begin node := stack.top; stack.top := stack.top^.next; dispose(node); end end;   function StackIsEmpty(stack: tStack):Boolean; begin StackIsEmpty := stack.top = nil end;   procedure PushToStack(var stack: tStack; value: integer); var node: pStackNode; begin new(node); node^.next := stack.top; node^.data := value; stack.top := node end;   { may only be called on a non-empty stack! } function PopFromStack(var stack: tStack): integer; var node: pStackNode; begin node := stack.top; stack.top := node^.next; PopFromStack := node^.data; dispose(node); 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)
#Rust
Rust
const VECTORS: [(isize, isize); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)];   pub fn spiral_matrix(size: usize) -> Vec<Vec<u32>> { let mut matrix = vec![vec![0; size]; size]; let mut movement = VECTORS.iter().cycle(); let (mut x, mut y, mut n) = (-1, 0, 1..);   for (move_x, move_y) in std::iter::once(size) .chain((1..size).rev().flat_map(|n| std::iter::repeat(n).take(2))) .flat_map(|steps| std::iter::repeat(movement.next().unwrap()).take(steps)) { x += move_x; y += move_y; matrix[y as usize][x as usize] = n.next().unwrap(); }   matrix }   fn main() { for i in spiral_matrix(4).iter() { for j in i.iter() { print!("{:>2} ", j); } println!(); } }
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.
#Elena
Elena
import extensions; import system'routines; import system'collections;   extension op { quickSort() { if (self.isEmpty()) { ^ self };   var pivot := self[0];   auto less := new ArrayList(); auto pivotList := new ArrayList(); auto more := new ArrayList();   self.forEach:(item) { if (item < pivot) { less.append(item) } else if (item > pivot) { more.append(item) } else { pivotList.append(item) } };   less := less.quickSort(); more := more.quickSort();   less.appendRange(pivotList); less.appendRange(more);   ^ less } }   public program() { var list := new int[]{3, 14, 1, 5, 9, 2, 6, 3};   console.printLine("before:", list.asEnumerable()); console.printLine("after :", list.quickSort().asEnumerable()); }
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
#Standard_ML
Standard ML
structure PilePriority = struct type priority = int fun compare (x, y) = Int.compare (y, x) (* we want min-heap *) type item = int list val priority = hd end   structure PQ = LeftPriorityQFn (PilePriority)   fun sort_into_piles n = let val piles = DynamicArray.array (length n, []) fun bsearch_piles x = let fun aux (lo, hi) = if lo > hi then lo else let val mid = (lo + hi) div 2 in if hd (DynamicArray.sub (piles, mid)) < x then aux (mid+1, hi) else aux (lo, mid-1) end in aux (0, DynamicArray.bound piles) end fun f x = let val i = bsearch_piles x in DynamicArray.update (piles, i, x :: DynamicArray.sub (piles, i)) end in app f n; piles end   fun merge_piles piles = let val heap = DynamicArray.foldl PQ.insert PQ.empty piles fun f (heap, acc) = case PQ.next heap of NONE => acc | SOME (x::xs, heap') => f ((if null xs then heap' else PQ.insert (xs, heap')), x::acc) in rev (f (heap, [])) end   fun patience_sort n = merge_piles (sort_into_piles n)
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.
#Elena
Elena
import extensions;   extension op { insertionSort() = self.clone().insertionSort(0, self.Length - 1);   insertionSort(int first, int last) { for(int i := first + 1, i <= last, i += 1) { var entry := self[i]; int j := i;   while (j > first && self[j - 1] > entry) { self[j] := self[j - 1];   j -= 1 };   self[j] := entry } } }   public program() { var list := new int[]{3, 9, 4, 6, 8, 1, 7, 2, 5};   console.printLine("before:", list.asEnumerable()); console.printLine("after :", list.insertionSort().asEnumerable()); }
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.
#EasyLang
EasyLang
subr make_heap for i = 1 to n - 1 if data[i] > data[(i - 1) / 2] j = i while data[j] > data[(j - 1) / 2] swap data[j] data[(j - 1) / 2] j = (j - 1) / 2 . . . . subr sort n = len data[] call make_heap for i = n - 1 downto 1 swap data[0] data[i] j = 0 ind = 1 while ind < i if ind + 1 < i and data[ind + 1] > data[ind] ind += 1 . if data[j] < data[ind] swap data[j] data[ind] . j = ind ind = 2 * j + 1 . . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] call sort print data[]
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.
#Crystal
Crystal
def merge_sort(a : Array(Int32)) : Array(Int32) return a if a.size <= 1 m = a.size // 2 lt = merge_sort(a[0 ... m]) rt = merge_sort(a[m .. -1]) return merge(lt, rt) end   def merge(lt : Array(Int32), rt : Array(Int32)) : Array(Int32) result = Array(Int32).new until lt.empty? || rt.empty? result << (lt.first < rt.first ? lt.shift : rt.shift) end return result + lt + rt end   a = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] puts merge_sort(a) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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.
#REXX
REXX
/*REXX program sorts and displays an array using the pancake sort algorithm. */ call gen /*generate elements in the @. array.*/ call show 'before sort' /*display the BEFORE array elements.*/ say copies('▒', 60) /*display a separator line for eyeballs*/ call pancakeSort # /*invoke the pancake sort. Yummy. */ call show ' after sort' /*display the AFTER array elements. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ inOrder: parse arg n; do j=1 for n-1; k= j+1; if @.j>@.k then return 0; end; return 1 panFlip: parse arg y; do i=1 for (y+1)%2; yi=y-i+1; [email protected]; @[email protected]; @.yi=_; end; return show: do k=1 for #; say @element right(k,length(#)) arg(1)':' right(@.k,9); end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: fibs= '-55 -21 -1 -8 -8 -21 -55 0 0' /*some non─positive Fibonacci numbers, */ @element= right('element', 21) /* most Fibs of which are repeated.*/   /* ┌◄─┬──◄─ some paired bread primes which are of the form: (P-3)÷2 and 2∙P+3 */ /* │ │ where P is a prime. Bread primes are related to sandwich & meat primes*/ /* ↓ ↓ ──── ════ ───── ══════ ────── ══════ ────── ═══════ ─────── ═══════ ──────*/ bp=2 17 5 29 7 37 13 61 43 181 47 197 67 277 97 397 113 461 137 557 167 677 173 701, 797 1117 307 1237 1597 463 1861 467 $= bp fibs; #= words($) /*combine the two lists; get # of items*/ do j=1 for #; @.j= word($, j); end /*◄─── obtain a number from the $ list.*/ return /* [↑] populate the @. array with #s*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ pancakeSort: procedure expose @.; parse arg n .; if inOrder(n) then return do n=n by -1 for n-1  != @.1;  ?= 1; do j=2 to n; if @.j<=! then iterate  != @.j;  ?= j end /*j*/ call panFlip ?; call panFlip n end /*n*/; return
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].
#Oforth
Oforth
: selectSort(l) | b j i k s | l size ->s l asListBuffer ->b   s loop: i [ i dup ->k b at i 1 + s for: j [ b at(j) 2dup <= ifTrue: [ drop ] else: [ nip j ->k ] ] k i b at b put i swap b put ] b dup freeze ;
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].
#ooRexx
ooRexx
/*REXX **************************************************************** * program sorts an array using the selection-sort method. * derived from REXX solution * Note that ooRexx can process Elements of the stem argument (Use Arg) * 06.10.2010 Walter Pachl **********************************************************************/ call generate /*generate the array elements. */ call show 'before sort' /*show the before array elements,*/ call selectionSort x. /*invoke the selection sort. */ call show 'after sort' /*show the after array elements.*/ exit /*stick a fork in it, we're done.*/   selectionSort: Procedure Use Arg s. /* gain access to the argument */ do j=1 To s.0-1 t=s.j; p=j; do k=j+1 to s.0 if s.k<t then do; t=s.k; p=k; end end if p=j then iterate t=s.j; s.j=s.p; s.p=t end return   show: Parse Arg heading Say heading Do i=1 To x.0 Say i' 'x.i End say copies('-',79) Return return   generate: x.1='---The seven hills of Rome:---' x.2='==============================' x.3='Caelian' x.4='Palatine' x.5='Capitoline' x.6='Virminal' x.7='Esquiline' x.8='Quirinal' x.9='Aventine' x.0=9 return
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.
#PicoLisp
PicoLisp
(de soundex (Str) (pack (pad -4 (cons (uppc (char (char Str))) (head 3 (let Last NIL (extract '((C) (and (setq C (case (uppc C) (`(chop "BFPV") "1") (`(chop "CGJKQSXZ") "2") (("D" "T") "3") ("L" "4") (("M" "N") "5") ("R" "6") ) ) (<> Last C) (setq Last C) ) ) (cdr (chop Str)) ) ) ) ) ) ) )
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.
#Vlang
Vlang
fn shell(mut arr []int, n int) { mut j := 0 for h := n; h /= 2; { for i := h; i < n; i++ { t := arr[i] for j = i; j >= h && t < arr[j - h]; j -= h { arr[j] = arr[j - h] } arr[j] = t } } }   fn main() { mut arr := [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] n := arr.len println('Input: ' + arr.str()) shell(mut arr, n) println('Output: ' + arr.str()) }
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.
#Whitespace
Whitespace
var shellSort = Fn.new { |a| var n = a.count var gaps = [701, 301, 132, 57, 23, 10, 4, 1] for (gap in gaps) { if (gap < n) { for (i in gap...n) { var t = a[i] var j = i while (j >= gap && a[j-gap] > t) { a[j] = a[j - gap] j = j - gap } a[j] = t } } } }   var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ] for (a in as) { System.print("Before: %(a)") shellSort.call(a) System.print("After : %(a)") System.print() }
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
#Perl
Perl
sub empty{ not @_ }
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)
#Scala
Scala
class Folder(){ var dir = (1,0) var pos = (-1,0) def apply(l:List[Int], a:Array[Array[Int]]) = { var (x,y) = pos //start position var (dx,dy) = dir //direction l.foreach {e => x = x + dx; y = y + dy; a(y)(x) = e } //copy l elements to array using current direction pos = (x,y) dir = (-dy, dx) //turn } } def spiral(n:Int) = { def dup(n:Int) = (1 to n).flatMap(i=>List(i,i)).toList val folds = n :: dup(n-1).reverse //define fold part lengths   var array = new Array[Array[Int]](n,n) val fold = new Folder()   var seq = (0 until n*n).toList //sequence to fold folds.foreach {len => fold(seq.take(len),array); seq = seq.drop(len)} array }
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.
#Elixir
Elixir
defmodule Sort do def qsort([]), do: [] def qsort([h | t]) do {lesser, greater} = Enum.split_with(t, &(&1 < h)) qsort(lesser) ++ [h] ++ qsort(greater) end end
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of numbers (of any convenient size) into ascending order using   Patience sorting. Related task   Longest increasing subsequence
#Tcl
Tcl
package require Tcl 8.6   proc patienceSort {items} { # Make the piles set piles {} foreach item $items { set p [lsearch -bisect -index end $piles $item] if {$p == -1} { lappend piles [list $item] } else { lset piles $p end+1 $item } } # Merge the piles; no suitable builtin, alas set indices [lrepeat [llength $piles] 0] set result {} while 1 { set j 0 foreach pile $piles i $indices { set val [lindex $pile $i] if {$i < [llength $pile] && (![info exist min] || $min > $val)} { set k $j set next [incr i] set min $val } incr j } if {![info exist min]} break lappend result $min unset min lset indices $k $next } return $result }
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.
#Elixir
Elixir
defmodule Sort do def insert_sort(list) when is_list(list), do: insert_sort(list, [])   def insert_sort([], sorted), do: sorted def insert_sort([h | t], sorted), do: insert_sort(t, insert(h, sorted))   defp insert(x, []), do: [x] defp insert(x, sorted) when x < hd(sorted), do: [x | sorted] defp insert(x, [h | t]), do: [h | insert(x, t)] 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.
#EchoLisp
EchoLisp
  (lib 'heap)   (define (heap-sort list) (define heap (make-heap < )) ;; make a min heap (list->heap list heap) (while (not (heap-empty? heap)) (push 'stack (heap-pop heap))) (stack->list 'stack))   (define L (shuffle (iota 15))) → (9 4 0 12 8 3 10 7 11 2 5 6 14 13 1) (heap-sort L) → (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)    
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.
#Curry
Curry
-- merge sort: sorting two lists by merging the sorted first -- and second half of the list   sort :: ([a] -> [a] -> [a] -> Success) -> [a] -> [a] -> Success   sort merge xs ys = if length xs < 2 then ys =:= xs else sort merge (firsthalf xs) us & sort merge (secondhalf xs) vs & merge us vs ys where us,vs free     intMerge :: [Int] -> [Int] -> [Int] -> Success   intMerge [] ys zs = zs =:= ys intMerge (x:xs) [] zs = zs =:= x:xs intMerge (x:xs) (y:ys) zs = if (x > y) then intMerge (x:xs) ys us & zs =:= y:us else intMerge xs (y:ys) vs & zs =:= x:vs where us,vs free   firsthalf xs = take (length xs `div` 2) xs secondhalf xs = drop (length xs `div` 2) xs       goal1 xs = sort intMerge [3,1,2] xs goal2 xs = sort intMerge [3,1,2,5,4,8] xs goal3 xs = sort intMerge [3,1,2,5,4,8,6,7,2,9,1,4,3] xs
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.
#Ring
Ring
  pancakeList = [6, 7, 8, 9, 2, 5, 3, 4, 1] flag = 0 see "Before :" + nl for n = 1 to len(pancakeList) see pancakeList[n] + " " next see nl   pancakeSort(pancakeList)   see "After :" + nl for n = 1 to len(pancakeList) see pancakeList[n] + " " next see nl   func pancakeSort A n = len(A) while flag = 0 flag = 1 for i = 1 to n-1 if A[i] < A[i+1] temp = A[i] A[i] = A[i+1] A [i+1] = temp flag = 0 ok next end return 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.
#Ruby
Ruby
class Array def pancake_sort! num_flips = 0 (self.size-1).downto(1) do |end_idx| max = self[0..end_idx].max max_idx = self[0..end_idx].index(max) next if max_idx == end_idx   if max_idx > 0 self[0..max_idx] = self[0..max_idx].reverse p [num_flips += 1, self] if $DEBUG end   self[0..end_idx] = self[0..end_idx].reverse p [num_flips += 1, self] if $DEBUG end self end end   p a = (1..9).to_a.shuffle p a.pancake_sort!
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].
#Oz
Oz
declare proc {SelectionSort Arr} proc {Swap K L} Arr.K := (Arr.L := Arr.K) end Low = {Array.low Arr} High = {Array.high Arr} in %% for every index I of the array for I in Low..High do %% find the index of the minimum element %% with an index >= I Min = {NewCell Arr.I} MinIndex = {NewCell I} in for J in I..High do if Arr.J < @Min then Min := Arr.J MinIndex := J end end %% and put that minimum element to the left {Swap @MinIndex I} end end   A = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)} in {SelectionSort A} {Show {Array.toRecord unit A}}
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.
#PL.2FI
PL/I
Soundex: procedure (pword) returns (character(4)); declare pword character (*) varying, value character (length(pword)) varying; declare word character (length(pword)); declare (prevCode, currCode) character (1); declare alphabet CHARACTER (26) STATIC INITIAL ('AEIOUHWYBFPVCGJKQSXZDTLMNR'); declare replace character (26) static initial ('00000000111122222222334556'); declare i fixed binary;   word = pword;   /* Buffer to build up with character codes */ value = '';   /* Make sure the word is at least two characters in length. */ if length(word) <= 1 then return (word);   word = uppercase(word); /* Convert to uppercase. */   /* The current and previous character codes */ prevCode = '0';   value = substr(word, 1, 1); /* The first character is unchanged. */   word = Translate (word, replace, alphabet);   /* Loop through the remaining characters ... */ do i = 2 to length(word); currCode = substr(word, i, 1); /* Check to see if the current code is the same as the last one */ if currCode ^= prevCode & currCode ^= '0' then /* If the current code is a vowel, ignore it. */ value = value || currCode; /* Set the new previous character code */ prevCode = currCode; end; /* of do i = ... */   return ( left(value, 4, '0') ); /* Pad, if necessary. */   end 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.
#Wren
Wren
var shellSort = Fn.new { |a| var n = a.count var gaps = [701, 301, 132, 57, 23, 10, 4, 1] for (gap in gaps) { if (gap < n) { for (i in gap...n) { var t = a[i] var j = i while (j >= gap && a[j-gap] > t) { a[j] = a[j - gap] j = j - gap } a[j] = t } } } }   var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ] for (a in as) { System.print("Before: %(a)") shellSort.call(a) System.print("After : %(a)") System.print() }
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
#Phix
Phix
with javascript_semantics -- comparing a simple implementation against using the builtins: sequence stack = {} procedure push_(object what) stack = append(stack,what) end procedure function pop_() object what = stack[$] stack = stack[1..$-1] return what end function function empty_() return length(stack)=0 end function ?empty_() -- 1 push_(5) ?empty_() -- 0 push_(6) ?pop_() -- 6 ?pop_() -- 5 ?empty_() -- 1 ?"===builtins===" requires("1.0.2") -- (latest bugfixes, plus top renamed as peep, for p2js) integer sid = new_stack() ?stack_empty(sid) -- 1 push(sid,5) ?stack_empty(sid) -- 0 push(sid,6) --?peep(sid) -- 6 (leaving it there) ?pop(sid) -- 6 ?pop(sid) -- 5 ?stack_empty(sid) -- 1
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)
#Scilab
Scilab
function a = spiral(n) a = ones(n*n, 1) v = ones(n, 1) u = -n*v; i = n for k = n-1:-1:1 j = 1:k u(j) = -u(j) a(j+i) = u(j) v(j) = -v(j) a(j+(i+k)) = v(j) i = i+2*k end a(cumsum(a)) = (1:n*n)' a = matrix(a, n, n)'-1 endfunction   -->spiral(5) ans =   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.
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.
#Erlang
Erlang
  -module( quicksort ).   -export( [qsort/1] ).   qsort([]) -> []; qsort([X|Xs]) -> qsort([ Y || Y <- Xs, Y < X]) ++ [X] ++ qsort([ Y || Y <- Xs, Y >= X]).  
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
#Wren
Wren
import "/sort" for Cmp   var patienceSort = Fn.new { |a| var size = a.count if (size < 2) return var cmp = Cmp.default(a[0]) var piles = [] for (e in a) { var outer = false for (pile in piles) { if (cmp.call(pile[-1], e) > 0) { pile.add(e) outer = true break } } if (!outer) piles.add([e]) } for (i in 0...size) { var min = piles[0][-1] var minPileIndex = 0 for (j in 1...piles.count) { if (cmp.call(piles[j][-1], min) < 0) { min = piles[j][-1] minPileIndex = j } } a[i] = min var minPile = piles[minPileIndex] minPile.removeAt(-1) if (minPile.count == 0) piles.removeAt(minPileIndex) } }   var ia = [4, 65, 2, -31, 0, 99, 83, 782, 1] patienceSort.call(ia) System.print(ia)   var ca = ["n", "o", "n", "z", "e", "r", "o", "s", "u", "m"] patienceSort.call(ca) System.print(ca)   var sa = ["dog", "cow", "cat", "ape", "ant", "man", "pig", "ass", "gnu"] patienceSort.call(sa) System.print(sa)
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.
#Emacs_Lisp
Emacs Lisp
(defun min-or-max-of-a-list (numbers comparator) "Return minimum or maximum of NUMBERS using COMPARATOR." (let ((extremum (car numbers))) (dolist (n (cdr numbers)) (when (funcall comparator n extremum) (setq extremum n))) extremum))   (defun remove-number-from-list (numbers n) "Return NUMBERS without N. If n is present twice or more, it will be removed only once." (let (result) (while numbers (let ((number (pop numbers))) (if (= number n) (while numbers (push (pop numbers) result)) (push number result)))) (nreverse result)))   (defun insertion-sort (numbers comparator) "Return sorted list of NUMBERS using COMPARATOR." (if numbers (let ((extremum (min-or-max-of-a-list numbers comparator))) (cons extremum (insertion-sort (remove-number-from-list numbers extremum) comparator))) nil))   (insertion-sort '(1 2 3 9 8 7 25 12 3 2 1) #'>)
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.
#Eiffel
Eiffel
  class HEAPSORT   feature   sort_array (ar: ARRAY [INTEGER]) -- Sorts array 'ar' in ascending order. require not_empty: ar.count > 0 local i, j, r, l, m, n: INTEGER sorted: BOOLEAN do n := ar.count j := 0 i := 0 m := 0 r := n l := (n // 2)+1 from until sorted loop if l > 1 then l := l - 1 m := ar[l] else m := ar[r] ar[r] := ar[1] r := r - 1 if r = 1 then ar[1]:=m sorted := True end end if not sorted then i := l j := l * 2 from until j > r loop if (j < r) and (ar[j] < ar[j + 1]) then j := j + 1 end if m < ar[j] then ar[i]:= ar[j] i := j j := j + i else j := r + 1 end end ar[i]:= m end end ensure sorted: is_sorted(ar) end   feature{NONE}   is_sorted (ar: ARRAY [INTEGER]): BOOLEAN --- Is 'ar' sorted in ascending order? local i: INTEGER do Result := True from i := ar.lower until i >= ar.upper loop if ar [i] > ar [i + 1] then Result := False end i := i + 1 end end   end  
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.
#D
D
import std.stdio, std.algorithm, std.array, std.range;   T[] mergeSorted(T)(in T[] D) /*pure nothrow @safe*/ { if (D.length < 2) return D.dup; return [D[0 .. $ / 2].mergeSorted, D[$ / 2 .. $].mergeSorted] .nWayUnion.array; }   void main() { [3, 4, 2, 5, 1, 6].mergeSorted.writeln; }
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.
#Rust
Rust
fn pancake_sort<T: Ord>(v: &mut [T]) { let len = v.len(); // trivial case -- no flips if len < 2 { return; } for i in (0..len).rev() { // find index of the maximum element within `v[0..i]` (inclusive) let max_index = v.iter() .take(i + 1) .enumerate() .max_by_key(|&(_, elem)| elem) .map(|(idx, _)| idx) // safe because we already checked if `v` is empty .unwrap(); // if `max_index` is not where it's supposed to be // do two flips to move it to `i` if max_index != i { flip(v, max_index); flip(v, i); } } }   // function to flip a section of a mutable collection from 0..num (inclusive) fn flip<E: PartialOrd>(v: &mut [E], num: usize) { v[0..num + 1].reverse(); }   fn main() { // Sort numbers let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; println!("Before: {:?}", numbers); pancake_sort(&mut numbers); println!("After: {:?}", numbers);   // Sort strings let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"]; println!("Before: {:?}", strings); pancake_sort(&mut strings); println!("After: {:?}", strings); }
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.
#Sidef
Sidef
func pancake(a) { for idx in ^(a.end) { var min = idx for i in (idx+1 .. a.end) { min = i if (a[min] > a[i]) } next if (a[min] == a[idx]) a[min..a.end] = [a[min..a.end]].reverse... a[idx..a.end] = [a[idx..a.end]].reverse... } return a }   var arr = 10.of{ 100.irand } say "Before: #{arr}" say "After: #{pancake(arr)}"
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].
#PARI.2FGP
PARI/GP
selectionSort(v)={ for(i=1,#v-1, my(mn=i,t); for(j=i+1,#v, if(v[j]<v[mn],mn=j) ); t=v[mn]; v[mn]=v[i]; v[i]=t ); v };
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.
#PowerShell
PowerShell
  function Get-Soundex { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string[]] $InputObject )   Begin { $characterGroup = [PSCustomObject]@{ 1 = @('B','F','P','V') 2 = @('C','G','J','K','Q','S','X','Z') 3 = @('D','T') 4 = @('L') 5 = @('M','N') 6 = @('R') }   function ConvertTo-SoundexDigit ([char]$Character) { switch ($Character) { {$_ -in $characterGroup.1} {return 1} {$_ -in $characterGroup.2} {return 2} {$_ -in $characterGroup.3} {return 3} {$_ -in $characterGroup.4} {return 4} {$_ -in $characterGroup.5} {return 5} {$_ -in $characterGroup.6} {return 6} Default {return 0} } } } Process { foreach ($String in $InputObject) { $originalString = $String $String = $String.ToUpper() $isHorWcharacter = $false $soundex = New-Object -TypeName System.Text.StringBuilder   $soundex.Append($String[0]) | Out-Null   for ($i = 1; $i -lt $String.Length; $i++) { $currentCharacterDigit = ConvertTo-SoundexDigit $String[$i]   if ($currentCharacterDigit -ne 0) { if ($i -eq (ConvertTo-SoundexDigit $String[$i-1])) { continue }   if (($i -gt 2) -and ($isHorWcharacter) -and ($currentCharacterDigit -eq (ConvertTo-SoundexDigit $String[$i-2]))) { continue }   $soundex.Append($currentCharacterDigit) | Out-Null }   $isHorWcharacter = $String[$i] -in @('H','W') }   $soundexTail = ($soundex.ToString().Substring(1)).TrimStart((ConvertTo-SoundexDigit $String[0]).ToString())   [PSCustomObject]@{ String = $originalString Soundex = ($soundex[0] + $soundexTail).PadRight(4,"0").Substring(0,4) } } } }  
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.
#XPL0
XPL0
  include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings     proc SSort(A, N); \Shell sort array in ascending order char A; \address of array int N; \number of elements in array (size) int I, J, Gap, JG, T; [Gap:= N>>1; while Gap > 0 do [for I:= Gap to N-1 do [J:= I - Gap; loop [JG:= J + Gap; if A(J) <= A(JG) then quit; T:= A(J); A(J):= A(JG); A(JG):= T; \swap elements J:= J - Gap; if J < 0 then quit; ]; ]; Gap:= Gap>>1; ]; ]; \SSort     func StrLen(Str); \Return number of characters in an ASCIIZ string char Str; int I; for I:= 0 to -1>>1-1 do if Str(I) = 0 then return I;     char Str; [Str:= "Pack my box with five dozen liquor jugs."; SSort(Str, StrLen(Str)); Text(0, Str); CrLf(0); ]
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
#Yabasic
Yabasic
export sub shell_sort(x()) // Shell sort based on insertion sort   local gap, i, j, first, last, tempi, tempj   last = arraysize(x(),1) gap = int(last / 10) + 1 while(TRUE) first = gap + 1 for i = first to last tempi = x(i) j = i - gap while(TRUE) tempj = x(j) if tempi >= tempj then j = j + gap break end if x(j+gap) = tempj if j <= gap then break end if j = j - gap wend x(j) = tempi next i if gap = 1 then return else gap = int(gap / 3.5) + 1 end if wend end sub   if peek$("library") = "main" then   clear screen   ITEMS = 100 dim numeros(ITEMS)   for n = 1 to ITEMS numeros(n) = ran(ITEMS + 1) next n   print time$ shell_sort(numeros()) print time$ print "Press a key to see ordered numbers." inkey$   for n = 1 to ITEMS print numeros(n),", "; next n   end if
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
#PHP
PHP
$stack = array();   empty( $stack ); // true   array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2;   empty( $stack ); // false   echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
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)
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: matrix is array array integer;   const func matrix: spiral (in integer: n) is func result var matrix: myArray is matrix.value; local var integer: i is 0; var integer: dx is 1; var integer: dy is 0; var integer: x is 1; var integer: y is 1; var integer: nx is 0; var integer: ny is 0; var integer: swap is 0; begin myArray := n times n times 0; for i range 1 to n**2 do myArray[x][y] := i; nx := x + dx; ny := y + dy; if nx >= 1 and nx <= n and ny >= 1 and ny <= n and myArray[nx][ny] = 0 then x := nx; y := ny; else swap := dx; dx := -dy; dy := swap; x +:= dx; y +:= dy; end if; end for; end func;   const proc: writeMatrix (in matrix: myArray) is func local var integer: x is 0; var integer: y is 0; begin for key y range myArray do for key x range myArray[y] do write(myArray[x][y] lpad 4); end for; writeln; end for; end func;   const proc: main is func begin writeMatrix(spiral(5)); end func;
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.
#Emacs_Lisp
Emacs Lisp
(require 'seq)   (defun quicksort (xs) (if (null xs) () (let* ((head (car xs)) (tail (cdr xs)) (lower-part (quicksort (seq-filter (lambda (x) (<= x head)) tail))) (higher-part (quicksort (seq-filter (lambda (x) (> x head)) tail)))) (append lower-part (list head) higher-part))))
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
#zkl
zkl
fcn patienceSort(ns){ piles:=L(); foreach n in (ns){ newPile:=True; // create list of sorted lists foreach p in (piles){ if(n>=p[-1]) { p.append(n); newPile=False; break; } } if(newPile)piles.append(L(n)); } // merge sort the piles r:=Sink(List); while(piles){ mins:=piles.apply("get",0).enumerate(); min :=mins.reduce(fcn(a,b){ (a[1]<b[1]) and a or b },mins[0])[0]; r.write(piles[min].pop(0)); if(not piles[min]) piles.del(min); } r.close(); }
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.
#Erlang
Erlang
-module(sort). -export([insertion/1]).   insertion(L) -> lists:foldl(fun insert/2, [], L).   insert(X,[]) -> [X]; insert(X,L=[H|_]) when X =< H -> [X|L]; insert(X,[H|T]) -> [H|insert(X, T)].
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.
#Elixir
Elixir
defmodule Sort do def heapSort(list) do len = length(list) heapify(List.to_tuple(list), div(len - 2, 2)) |> heapSort(len-1) |> Tuple.to_list end   defp heapSort(a, finish) when finish > 0 do swap(a, 0, finish) |> siftDown(0, finish-1) |> heapSort(finish-1) end defp heapSort(a, _), do: a   defp heapify(a, start) when start >= 0 do siftDown(a, start, tuple_size(a)-1) |> heapify(start-1) end defp heapify(a, _), do: a   defp siftDown(a, root, finish) when root * 2 + 1 <= finish do child = root * 2 + 1 if child + 1 <= finish and elem(a,child) < elem(a,child + 1), do: child = child + 1 if elem(a,root) < elem(a,child), do: swap(a, root, child) |> siftDown(child, finish), else: a end defp siftDown(a, _root, _finish), do: a   defp swap(a, i, j) do {vi, vj} = {elem(a,i), elem(a,j)} a |> put_elem(i, vj) |> put_elem(j, vi) end end   (for _ <- 1..20, do: :rand.uniform(20)) |> IO.inspect |> Sort.heapSort |> IO.inspect
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.
#Dart
Dart
void main() { MergeSortInDart sampleSort = MergeSortInDart();   List<int> theResultingList = sampleSort.sortTheList([54, 89, 125, 47899, 32, 61, 42, 895647, 215, 345, 6, 21, 2, 78]);   print('Here\'s the sorted list: ${theResultingList}'); }   /////////////////////////////////////   class MergeSortInDart {   List<int> sortedList;   // In Dart we often put helper functions at the bottom. // You could put them anywhere, we just like it this way // for organizational purposes. It's nice to be able to // read them in the order they're called.   // Start here List<int> sortTheList(List<int> sortThis){ // My parameters are listed vertically for readability. Dart // doesn't care how you list them, vertically or horizontally. sortedList = mSort( sortThis, sortThis.sublist(0, sortThis.length), sortThis.length, ); return sortThis; }   mSort( List<int> sortThisList, List<int> tempList, int thisListLength) {   if (thisListLength == 1) { return; }   // In Dart using ~/ is more efficient than using .floor() int middle = (thisListLength ~/ 2);   // If you use something in a try/on/catch/finally block then // be sure to declare it outside the block (for scope) List<int> tempLeftList;   // This was used for troubleshooting. It was left here to show // how a basic block try/on can be better than a debugPrint since // it won't print unless there's a problem. try { tempLeftList = tempList.sublist(0, middle); } on RangeError { print( 'tempLeftList length = ${tempList.length}, thisListLength ' 'was supposedly $thisListLength and Middle was $middle'); }   // If you see "myList.getRange(x,y)" that's a sign the code is // from Dart 1 and needs to be updated. It's "myList.sublist" in Dart 2 List<int> tempRightList = tempList.sublist(middle);   // Left side. mSort( tempLeftList, sortThisList.sublist(0, middle), middle, );   // Right side. mSort( tempRightList, sortThisList.sublist(middle), sortThisList.length - middle, );   // Merge it. dartMerge( tempLeftList, tempRightList, sortThisList, ); }   dartMerge( List<int> leftSide, List<int> rightSide, List<int> sortThisList, ) { int index = 0; int elementValue;   // This should be human readable. while (leftSide.isNotEmpty && rightSide.isNotEmpty) { if (rightSide[0] < leftSide[0]) { elementValue = rightSide[0]; rightSide.removeRange(0, 1); } else { elementValue = leftSide[0]; leftSide.removeRange(0, 1); } sortThisList[index++] = elementValue; }   while (leftSide.isNotEmpty) { elementValue = leftSide[0]; leftSide.removeRange(0, 1); sortThisList[index++] = elementValue; }   while (rightSide.isNotEmpty) { elementValue = rightSide[0]; rightSide.removeRange(0, 1); sortThisList[index++] = elementValue; } sortedList = sortThisList; } }
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.
#Swift
Swift
import Foundation   struct PancakeSort { var arr:[Int]   mutating func flip(n:Int) { for i in 0 ..< (n + 1) / 2 { swap(&arr[n - i], &arr[i]) } println("flip(0.. \(n)): \(arr)") }   func minmax(n:Int) -> [Int] { var xm = arr[0] var xM = arr[0] var posm = 0 var posM = 0   for i in 1..<n { if (arr[i] < xm) { xm = arr[i] posm = i } else if (arr[i] > xM) { xM = arr[i] posM = i } }   return [posm, posM] }   mutating func sort(var n:Int, var dir:Int) { if n == 0 { return }   let mM = minmax(n) let bestXPos = mM[dir] let altXPos = mM[1 - dir] var flipped = false   if bestXPos == n - 1 { n-- } else if bestXPos == 0 { flip(n - 1) n-- } else if altXPos == n - 1 { dir = 1 - dir n-- flipped = true } else { flip(bestXPos) }   sort(n, dir: dir)   if flipped { flip(n) } } }   let arr = [2, 3, 6, 1, 4, 5, 10, 8, 7, 9] var a = PancakeSort(arr: arr) a.sort(arr.count, dir: 1) println(a.arr)