task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Insertion sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#REXX
REXX
/*REXX program sorts a stemmed array (has characters) using the insertion sort algorithm*/ call gen /*generate the array's (data) elements.*/ call show 'before sort' /*display the before array elements. */ say copies('▒', 85) /*display a separator line (a fence). */ call insertionSort # /*invoke the insertion sort. */ call show ' after sort' /*display the after array elements. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: @.=; @.1 = "---Monday's Child Is Fair of Face (by Mother Goose)---" @.2 = "=======================================================" @.3 = "Monday's child is fair of face;" @.4 = "Tuesday's child is full of grace;" @.5 = "Wednesday's child is full of woe;" @.6 = "Thursday's child has far to go;" @.7 = "Friday's child is loving and giving;" @.8 = "Saturday's child works hard for a living;" @.9 = "But the child that is born on the Sabbath day" @.10 = "Is blithe and bonny, good and gay." do #=1 while @.#\==''; end; #= #-1 /*determine how many entries in @ array*/ return /* [↑] adjust # for the DO loop index.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ insertionSort: procedure expose @.; parse arg # do i=2 to #; $= @.i; do j=i-1 by -1 to 1 while @.j>$ _= j + 1; @._= @.j end /*j*/ _= j + 1; @._= $ end /*i*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: do j=1 for #; say ' element' right(j,length(#)) arg(1)": " @.j; end; return
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.
#Ruby
Ruby
def merge_sort(m) return m if m.length <= 1   middle = m.length / 2 left = merge_sort(m[0...middle]) right = merge_sort(m[middle..-1]) merge(left, right) end   def merge(left, right) result = [] until left.empty? || right.empty? result << (left.first<=right.first ? left.shift : right.shift) end result + left + right end   ary = [7,6,5,9,8,4,3,1,2,0] p merge_sort(ary) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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.
#PowerShell
PowerShell
Function SortThree( [Array] $data ) { if( $data[ 0 ] -gt $data[ 1 ] ) { if( $data[ 0 ] -lt $data[ 2 ] ) { $data = $data[ 1, 0, 2 ] } elseif ( $data[ 1 ] -lt $data[ 2 ] ){ $data = $data[ 1, 2, 0 ] } else { $data = $data[ 2, 1, 0 ] } } else { if( $data[ 0 ] -gt $data[ 2 ] ) { $data = $data[ 2, 0, 1 ] } elseif( $data[ 1 ] -gt $data[ 2 ] ) { $data = $data[ 0, 2, 1 ] } } $data }   Function QuickSort( [Array] $data, $rand = ( New-Object Random ) ) { $datal = $data.length if( $datal -gt 3 ) { [void] $datal-- $median = ( SortThree $data[ 0, ( $rand.Next( 1, $datal - 1 ) ), -1 ] )[ 1 ] $lt = @() $eq = @() $gt = @() $data | ForEach-Object { if( $_ -lt $median ) { $lt += $_ } elseif( $_ -eq $median ) { $eq += $_ } else { $gt += $_ } } $lt = ( QuickSort $lt $rand ) $gt = ( QuickSort $gt $rand ) $data = @($lt) + $eq + $gt } elseif( $datal -eq 3 ) { $data = SortThree( $data ) } elseif( $datal -eq 2 ) { if( $data[ 0 ] -gt $data[ 1 ] ) { $data = $data[ 1, 0 ] } } $data }   QuickSort 5,3,1,2,4 QuickSort 'e','c','a','b','d' QuickSort 0.5,0.3,0.1,0.2,0.4 $l = 100; QuickSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } )
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[CocktailShakerSort] CocktailShakerSort[in_List] := Module[{x = in, swapped, begin = 1, end = Length[in] - 1}, swapped = True; While[swapped, swapped = False; Do[ If[x[[i]] > x[[i + 1]], x[[{i, i + 1}]] //= Reverse; swapped = True; ] , {i, begin, end} ]; end--;   Do[ If[x[[i]] > x[[i + 1]], x[[{i, i + 1}]] //= Reverse; swapped = True; ] , {i, end, begin, -1} ]; begin++; ]; x ] CocktailShakerSort[{44, 21, 5, 88, 52, 44, 36, 93, 66, 18, 88, 61, 45, 47, 47, 68, 19, 60}]
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Nim
Nim
proc cocktailShakerSort[T](a: var openarray[T]) =   var beginIdx = 0 var endIdx = a.len - 2   while beginIdx <= endIdx: var newBeginIdx = endIdx var newEndIdx = beginIdx for i in beginIdx..endIdx: if a[i] > a[i + 1]: swap a[i], a[i + 1] newEndIdx = i   endIdx = newEndIdx - 1   for i in countdown(endIdx, beginIdx): if a[i] > a[i + 1]: swap a[i], a[i + 1] newBeginIdx = i   beginIdx = newBeginIdx + 1   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] cocktailShakerSort a echo 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.
#Ring
Ring
  alist = [7,6,5,9,8,4,3,1,2,0] see insertionsort(alist)   func insertionsort blist for i = 1 to len(blist) value = blist[i] j = i - 1 while j >= 1 and blist[j] > value blist[j+1] = blist[j] j = j - 1 end blist[j+1] = value next return blist  
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.
#Ruby
Ruby
class Array def insertionsort! 1.upto(length - 1) do |i| value = self[i] j = i - 1 while j >= 0 and self[j] > value self[j+1] = self[j] j -= 1 end self[j+1] = value end self end end ary = [7,6,5,9,8,4,3,1,2,0] p ary.insertionsort! # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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.
#Rust
Rust
  fn merge<T: Copy + PartialOrd>(x1: &[T], x2: &[T], y: &mut [T]) { assert_eq!(x1.len() + x2.len(), y.len()); let mut i = 0; let mut j = 0; let mut k = 0; while i < x1.len() && j < x2.len() { if x1[i] < x2[j] { y[k] = x1[i]; k += 1; i += 1; } else { y[k] = x2[j]; k += 1; j += 1; } } if i < x1.len() { y[k..].copy_from_slice(&x1[i..]); } if j < x2.len() { y[k..].copy_from_slice(&x2[j..]); } }  
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.
#Prolog
Prolog
qsort( [], [] ). qsort( [H|U], S ) :- splitBy(H, U, L, R), qsort(L, SL), qsort(R, SR), append(SL, [H|SR], S).   % splitBy( H, U, LS, RS ) % True if LS = { L in U | L <= H }; RS = { R in U | R > H } splitBy( _, [], [], []). splitBy( H, [U|T], [U|LS], RS ) :- U =< H, splitBy(H, T, LS, RS). splitBy( H, [U|T], LS, [U|RS] ) :- U > H, splitBy(H, T, LS, RS).  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Perl
Perl
use strict; use warnings; use feature 'say';   sub cocktail_sort { my @a = @_; my ($min, $max) = (0, $#a-1); while (1) { my $swapped_forward = 0; for my $i ($min .. $max) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1 } } last if not $swapped_forward; $max -= 1;   my $swapped_backward = 0; for my $i (reverse $min .. $max) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_backward = 1; } } last if not $swapped_backward; $min += 1; } @a }   say join ' ', cocktail_sort( <t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g> );
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.
#Run_BASIC
Run BASIC
dim insSort(100) sortEnd = 0 global inSort global sortEnd   ' -- insert some random numbers --   for i = 1 to 20 a = int(1000 * rnd(1)) x = insertSort(a) next i   ' --- Print the Sorted Data -----   print "End Sort:";sortEnd ' number sorted for i = 1 to sortEnd print i;" ";insSort(i) ' location and sorted data next i wait   function insertSort(x) ' Insert Sort Function i = 1 while x > insSort(i) and i <= sortEnd i = i + 1 wend for j = sortEnd to i step -1 insSort(j + 1) = insSort(j) next j insSort(i) = x sortEnd = sortEnd + 1 end function
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.
#Scala
Scala
  import scala.language.implicitConversions   object MergeSort extends App {   def mergeSort(input: List[Int]): List[Int] = { def merge(left: List[Int], right: List[Int]): LazyList[Int] = (left, right) match { case (x :: xs, y :: ys) if x <= y => x #:: merge(xs, right) case (x :: xs, y :: ys) => y #:: merge(left, ys) case _ => if (left.isEmpty) right.to(LazyList) else left.to(LazyList) }   def sort(input: List[Int], length: Int): List[Int] = input match { case Nil | List(_) => input case _ => val middle = length / 2 val (left, right) = input splitAt middle merge(sort(left, middle), sort(right, middle + length % 2)).toList }   sort(input, input.length) }   }  
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.
#PureBasic
PureBasic
Procedure qSort(Array a(1), firstIndex, lastIndex) Protected low, high, pivotValue   low = firstIndex high = lastIndex pivotValue = a((firstIndex + lastIndex) / 2)   Repeat   While a(low) < pivotValue low + 1 Wend   While a(high) > pivotValue high - 1 Wend   If low <= high Swap a(low), a(high) low + 1 high - 1 EndIf   Until low > high   If firstIndex < high qSort(a(), firstIndex, high) EndIf   If low < lastIndex qSort(a(), low, lastIndex) EndIf EndProcedure   Procedure quickSort(Array a(1)) qSort(a(),0,ArraySize(a())) EndProcedure
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Phix
Phix
with javascript_semantics function cocktailShakerSort(sequence s) s = deep_copy(s) integer beginIdx = 1, endIdx = length(s)-1 while beginIdx <= endIdx do integer newBeginIdx = endIdx, newEndIdx = beginIdx for ii=beginIdx to endIdx do object si = s[ii], sn = s[ii+1] if si>sn then s[ii] = sn s[ii+1] = si newEndIdx = ii end if end for -- elements after `newEndIdx` are now in correct order endIdx = newEndIdx - 1 for ii=endIdx to beginIdx by -1 do object si = s[ii], sn = s[ii+1] if si>sn then s[ii] = sn s[ii+1] = si newBeginIdx = ii end if end for -- elements before `newBeginIdx` are now in correct order. beginIdx = newBeginIdx + 1 end while return s end function sequence s = shuffle(tagset(12)) ?{s,cocktailShakerSort(s)} s = {"one","two","three","four"} ?{s,cocktailShakerSort(s)}
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.
#Rust
Rust
fn insertion_sort<T: std::cmp::Ord>(arr: &mut [T]) { for i in 1..arr.len() { let mut j = i; while j > 0 && arr[j] < arr[j-1] { arr.swap(j, j-1); j = j-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.
#Scheme
Scheme
(define (merge-sort l gt?) (define (merge left right) (cond ((null? left) right) ((null? right) left) ((gt? (car left) (car right)) (cons (car right) (merge left (cdr right)))) (else (cons (car left) (merge (cdr left) right))))) (define (take l n) (if (zero? n) (list) (cons (car l) (take (cdr l) (- n 1))))) (let ((half (quotient (length l) 2))) (if (zero? half) l (merge (merge-sort (take l half) gt?) (merge-sort (list-tail l half) gt?)))))
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.
#Python
Python
def quickSort(arr): less = [] pivotList = [] more = [] if len(arr) <= 1: return arr else: pivot = arr[0] for i in arr: if i < pivot: less.append(i) elif i > pivot: more.append(i) else: pivotList.append(i) less = quickSort(less) more = quickSort(more) return less + pivotList + more   a = [4, 65, 2, -31, 0, 99, 83, 782, 1] a = quickSort(a)
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Python
Python
  """   Python example of   http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds   based on   http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort#Python   """   def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1   while beginIdx <= endIdx: newBeginIdx = endIdx newEndIdx = beginIdx for ii in range(beginIdx,endIdx): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newEndIdx = ii   endIdx = newEndIdx   for ii in range(endIdx,beginIdx-1,-1): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newBeginIdx = ii   beginIdx = newBeginIdx + 1   test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] cocktailshiftingbounds(test1) print(test1)   test2=list('big fjords vex quick waltz nymph') cocktailshiftingbounds(test2) print(''.join(test2))  
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.
#SASL
SASL
DEF sort () = () sort (a : x) = insert a (sort x) insert a () = a, insert a (b : x) = a < b -> a : b : x b : insert a x ?
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.
#Scala
Scala
def insertSort[X](list: List[X])(implicit ord: Ordering[X]) = { def insert(list: List[X], value: X) = list.span(x => ord.lt(x, value)) match { case (lower, upper) => lower ::: value :: upper } list.foldLeft(List.empty[X])(insert) }
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.
#Seed7
Seed7
const proc: mergeSort2 (inout array elemType: arr, in integer: lo, in integer: hi, inout array elemType: scratch) is func local var integer: mid is 0; var integer: k is 0; var integer: t_lo is 0; var integer: t_hi is 0; begin if lo < hi then mid := (lo + hi) div 2; mergeSort2(arr, lo, mid, scratch); mergeSort2(arr, succ(mid), hi, scratch); t_lo := lo; t_hi := succ(mid); for k range lo to hi do if t_lo <= mid and (t_hi > hi or arr[t_lo] <= arr[t_hi]) then scratch[k] := arr[t_lo]; incr(t_lo); else scratch[k] := arr[t_hi]; incr(t_hi); end if; end for; for k range lo to hi do arr[k] := scratch[k]; end for; end if; end func;   const proc: mergeSort2 (inout array elemType: arr) is func local var array elemType: scratch is 0 times elemType.value; begin scratch := length(arr) times elemType.value; mergeSort2(arr, 1, length(arr), scratch); 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.
#Qi
Qi
(define keep _ [] -> [] Pred [A|Rest] -> [A | (keep Pred Rest)] where (Pred A) Pred [_|Rest] -> (keep Pred Rest))   (define quicksort [] -> [] [A|R] -> (append (quicksort (keep (>= A) R)) [A] (quicksort (keep (< A) R))))   (quicksort [6 8 5 9 3 2 2 1 4 7])  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Raku
Raku
sub cocktail_sort ( @a ) { my ($min, $max) = 0, +@a - 2; loop { my $swapped_forward = 0; for $min .. $max -> $i { given @a[$i] cmp @a[$i+1] { when More { @a[ $i, $i+1 ] .= reverse; $swapped_forward = 1 } default {} } } last if not $swapped_forward; $max -= 1;   my $swapped_backward = 0; for ($min .. $max).reverse -> $i { given @a[$i] cmp @a[$i+1] { when More { @a[ $i, $i+1 ] .= reverse; $swapped_backward = 1 } default {} } } last if not $swapped_backward; $min += 1; } @a }   my @weights = (flat 0..9, 'A'..'F').roll(2 + ^4 .roll).join xx 100; say @weights.sort.Str eq @weights.&cocktail_sort.Str ?? 'ok' !! 'not ok';
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.
#Scheme
Scheme
(define (insert x lst) (if (null? lst) (list x) (let ((y (car lst)) (ys (cdr lst))) (if (<= x y) (cons x lst) (cons y (insert x ys))))))   (define (insertion-sort lst) (if (null? lst) '() (insert (car lst) (insertion-sort (cdr lst)))))   (insertion-sort '(6 8 5 9 3 2 1 4 7))
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.
#Sidef
Sidef
func merge(left, right) { var result = [] while (left && right) { result << [right,left].min_by{.first}.shift } result + left + right }   func mergesort(array) { var len = array.len len < 2 && return array   var (left, right) = array.part(len//2)   left = __FUNC__(left) right = __FUNC__(right)   merge(left, right) }   # Numeric sort var nums = rand(1..100, 10) say mergesort(nums)   # String sort var strings = rand('a'..'z', 10) say mergesort(strings)
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.
#Quackery
Quackery
[ stack ] is less ( --> s )   [ stack ] is same ( --> s )   [ stack ] is more ( --> s )   [ - -1 1 clamp 1+ ] is <=> ( n n --> n )   [ tuck take join swap put ] is append ( x s --> )   [ dup size 2 < if done [] less put [] same put [] more put behead swap witheach [ 2dup swap <=> [ table less same more ] append ] same append less take recurse same take join more take recurse join ] is quicksort ( [ --> [ )   [] 10 times [ i^ join ] 3 of dup echo cr quicksort echo cr
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#REXX
REXX
/*REXX program sorts an array using the cocktail─sort method with shifting bounds. */ call gen /*generate some array elements. */ call show 'before sort' /*show unsorted array elements. */ say copies('█', 101) /*show a separator line (a fence). */ call cocktailSort # /*invoke the cocktail sort subroutine. */ call show ' after sort' /*show sorted array elements. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ cocktailSort: procedure expose @.; parse arg N /*N: is number of items. */ end$= N - 1; beg$= 1 do while beg$ <= end$ beg$$= end$; end$$= beg$ do j=beg$ to end$; jp= j + 1 if @.j>@.jp then do; [email protected]; @[email protected]; @.jp=_; end$$=j; end end /*j*/ end$= end$$ - 1 do k=end$ to beg$ by -1; kp= k + 1 if @.k>@.kp then do; [email protected]; @[email protected]; @.kp=_; beg$$=k; end end /*k*/ beg$= beg$$ + 1 end /*while*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: @.= /*assign a default value for the stem. */ @.1 = '---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---' @.2 = '==========symbol====================pip======================================' @.3 = 'the juggler ◄─── I' @.4 = 'the high priestess [Popess] ◄─── II' @.5 = 'the empress ◄─── III' @.6 = 'the emperor ◄─── IV' @.7 = 'the hierophant [Pope] ◄─── V' @.8 = 'the lovers ◄─── VI' @.9 = 'the chariot ◄─── VII' @.10= 'justice ◄─── VIII' @.11= 'the hermit ◄─── IX' @.12= 'fortune [the wheel of] ◄─── X' @.13= 'strength ◄─── XI' @.14= 'the hanging man ◄─── XII' @.15= 'death [often unlabeled] ◄─── XIII' @.16= 'temperance ◄─── XIV' @.17= 'the devil ◄─── XV' @.18= 'lightning [the tower] ◄─── XVI' @.18= 'the stars ◄─── XVII' @.20= 'the moon ◄─── XVIII' @.21= 'the sun ◄─── XIX' @.22= 'judgment ◄─── XX' @.23= 'the world ◄─── XXI' @.24= 'the fool [often unnumbered] ◄─── XXII'   do #= 1 until @.#==''; end; #= #-1 /*find how many entries in the array. */ return /* [↑] adjust for DO loop advancement.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: w= length(#); do j=1 for # /*#: is the number of items in @. */ say 'element' right(j, w) arg(1)":" @.j end /*j*/ /* ↑ */ return /* └─────max width of any line.*/
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.
#Seed7
Seed7
const proc: insertionSort (inout array elemType: arr) is func local var integer: i is 0; var integer: j is 0; var elemType: help is elemType.value; begin for i range 2 to length(arr) do j := i; help := arr[i]; while j > 1 and arr[pred(j)] > help do arr[j] := arr[pred(j)]; decr(j); end while; arr[j] := help; end for; end func;
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.
#Sidef
Sidef
class Array { method insertion_sort { { |i| var j = i-1 var k = self[i] while ((j >= 0) && (k < self[j])) { self[j+1] = self[j] j-- } self[j+1] = k } << 1..self.end return self } }   var a = 10.of { 100.irand } say a.insertion_sort
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.
#Standard_ML
Standard ML
fun merge cmp ([], ys) = ys | merge cmp (xs, []) = xs | merge cmp (xs as x::xs', ys as y::ys') = case cmp (x, y) of GREATER => y :: merge cmp (xs, ys') | _ => x :: merge cmp (xs', ys) ; fun merge_sort cmp [] = [] | merge_sort cmp [x] = [x] | merge_sort cmp xs = let val ys = List.take (xs, length xs div 2) val zs = List.drop (xs, length xs div 2) in merge cmp (merge_sort cmp ys, merge_sort cmp zs) end ; merge_sort Int.compare [8,6,4,2,1,3,5,7,9]
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.
#R
R
qsort <- function(v) { if ( length(v) > 1 ) { pivot <- (min(v) + max(v))/2.0 # Could also use pivot <- median(v) c(qsort(v[v < pivot]), v[v == pivot], qsort(v[v > pivot])) } else v }   N <- 100 vs <- runif(N) system.time(u <- qsort(vs)) print(u)
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Rust
Rust
fn cocktail_shaker_sort<T: PartialOrd>(a: &mut [T]) { let mut begin = 0; let mut end = a.len(); if end == 0 { return; } end -= 1; while begin < end { let mut new_begin = end; let mut new_end = begin; for i in begin..end { if a[i + 1] < a[i] { a.swap(i, i + 1); new_end = i; } } end = new_end; let mut i = end; while i > begin { if a[i] < a[i - 1] { a.swap(i, i - 1); new_begin = i; } i -= 1; } begin = new_begin; } }   fn main() { let mut v = vec![5, 1, -6, 12, 3, 13, 2, 4, 0, 15]; println!("before: {:?}", v); cocktail_shaker_sort(&mut v); println!("after: {:?}", v); }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Swift
Swift
func cocktailShakerSort<T: Comparable>(_ a: inout [T]) { var begin = 0 var end = a.count if end == 0 { return } end -= 1 while begin < end { var new_begin = end var new_end = begin var i = begin while i < end { if a[i + 1] < a[i] { a.swapAt(i, i + 1) new_end = i } i += 1 } end = new_end i = end while i > begin { if a[i] < a[i - 1] { a.swapAt(i, i - 1) new_begin = i } i -= 1 } begin = new_begin } }   var array = [5, 1, -6, 12, 3, 13, 2, 4, 0, 15] print("before: \(array)") cocktailShakerSort(&array) print(" after: \(array)")   var array2 = ["one", "two", "three", "four", "five", "six", "seven", "eight"] print("before: \(array2)") cocktailShakerSort(&array2) print(" after: \(array2)")
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.
#SNOBOL4
SNOBOL4
* read data into an array A = table() i = 0 readln A<i = i + 1> = trim(input) :s(readln) aSize = i - 1   * sort array i = 1 loop1 value = A<i> j = i - 1 loop2 gt(j,0) gt(A<j>,value) :f(done2) A<j + 1> = A<j> j = j - 1 :(loop2) done2 A<j + 1> = value i = ?lt(i,aSize) i + 1 :s(loop1) i = 1   * output sorted data while output = A<i>; i = ?lt(i,aSize) i + 1 :s(while) 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.
#Swift
Swift
// Merge Sort in Swift 4.2 // Source: https://github.com/raywenderlich/swift-algorithm-club/tree/master/Merge%20Sort // NOTE: by use of generics you can make it sort arrays of any type that conforms to // Comparable protocol, however this is not always optimal   import Foundation   func mergeSort(_ array: [Int]) -> [Int] { guard array.count > 1 else { return array }   let middleIndex = array.count / 2   let leftPart = mergeSort(Array(array[0..<middleIndex])) let rightPart = mergeSort(Array(array[middleIndex..<array.count]))   func merge(left: [Int], right: [Int]) -> [Int] { var leftIndex = 0 var rightIndex = 0   var merged = [Int]() merged.reserveCapacity(left.count + right.count)   while leftIndex < left.count && rightIndex < right.count { if left[leftIndex] < right[rightIndex] { merged.append(left[leftIndex]) leftIndex += 1 } else if left[leftIndex] > right[rightIndex] { merged.append(right[rightIndex]) rightIndex += 1 } else { merged.append(left[leftIndex]) leftIndex += 1 merged.append(right[rightIndex]) rightIndex += 1 } }   while leftIndex < left.count { merged.append(left[leftIndex]) leftIndex += 1 }   while rightIndex < right.count { merged.append(right[rightIndex]) rightIndex += 1 }   return merged }   return merge(left: leftPart, right: rightPart) }
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.
#Racket
Racket
#lang racket (define (quicksort < l) (match l ['() '()] [(cons x xs) (let-values ([(xs-gte xs-lt) (partition (curry < x) xs)]) (append (quicksort < xs-lt) (list x) (quicksort < xs-gte)))]))
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#VBA
VBA
' Sorting algorithms/Cocktail sort with shifting bounds - VBA Function cocktailShakerSort(ByVal A As Variant) As Variant beginIdx = LBound(A) endIdx = UBound(A) - 1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newEndIdx = ii End If Next ii endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newBeginIdx = ii End If Next ii beginIdx = newBeginIdx + 1 Loop cocktailShakerSort = A End Function 'cocktailShakerSort Public Sub main() Dim B(20) As Variant For i = LBound(B) To UBound(B) B(i) = Int(Rnd() * 100) Next i Debug.Print Join(B, ", ") Debug.Print Join(cocktailShakerSort(B), ", ") End Sub
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.
#Stata
Stata
mata void insertion_sort(real vector a) { real scalar i, j, n, x   n = length(a) for (i=2; i<=n; i++) { x = a[i] for (j=i-1; j>=1; j--) { if (a[j] <= x) break a[j+1] = a[j] } a[j+1] = x } } 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.
#Tailspin
Tailspin
  templates mergesort templates merge @: $(2); [ $(1)... -> \( when <?($@merge<[](0)>) | ..$@merge(1)> do $ ! otherwise ^@merge(1) ! $ -> # \), $@...] ! end merge $ -> #   when <[](0..1)> do $! otherwise def half: $::length ~/ 2; [$(1..$half) -> mergesort, $($half+1..last) -> mergesort] -> merge ! end mergesort   [4,5,3,8,1,2,6,7,9,8,5] -> mergesort -> !OUT::write  
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.
#Raku
Raku
# Empty list sorts to the empty list multi quicksort([]) { () }   # Otherwise, extract first item as pivot... multi quicksort([$pivot, *@rest]) { # Partition. my $before := @rest.grep(* before $pivot); my $after := @rest.grep(* !before $pivot);   # Sort the partitions. flat quicksort($before), $pivot, quicksort($after) }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#VBScript
VBScript
' Sorting algorithms/Cocktail sort with shifting bounds - VBScript Function cocktailShakerSort(ByVal A) beginIdx = Lbound(A) endIdx = Ubound(A)-1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii+1) Then tmp=A(ii) : A(ii)=A(ii+1) : A(ii+1)=tmp newEndIdx = ii End If Next endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii+1) Then tmp=A(ii) : A(ii)=A(ii+1) : A(ii+1)=tmp newBeginIdx = ii End If Next beginIdx = newBeginIdx+1 Loop cocktailShakerSort=A End Function 'cocktailShakerSort Dim B(20) For i=Lbound(B) To Ubound(B) B(i)=Int(Rnd()*100) Next Wscript.Echo Join(cocktailShakerSort(B)," ")  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Visual_Basic_.NET
Visual Basic .NET
' Sorting algorithms/Cocktail sort with shifting bounds - VB.Net Private Sub Cocktail_Shaker_Sort() Dim A(20), tmp As Long 'or Integer Long Single Double String Dim i, beginIdx, endIdx, newBeginIdx, newEndIdx As Integer 'Generate the list For i = LBound(A) To UBound(A) A(i) = Int(Rnd() * 100) Next i 'Sort the list beginIdx = LBound(A) endIdx = UBound(A) - 1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii + 1) Then tmp = A(ii) : A(ii) = A(ii + 1) : A(ii + 1) = tmp newEndIdx = ii End If Next ii endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii + 1) Then tmp = A(ii) : A(ii) = A(ii + 1) : A(ii + 1) = tmp newBeginIdx = ii End If Next ii beginIdx = newBeginIdx + 1 Loop 'Display the sorted list Debug.Print(String.Join(", ", A)) End Sub 'Cocktail_Shaker_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.
#Swift
Swift
func insertionSort<T:Comparable>(inout list:[T]) { for i in 1..<list.count { var j = i   while j > 0 && list[j - 1] > list[j] { swap(&list[j], &list[j - 1]) j-- } } }
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.
#Tcl
Tcl
package require Tcl 8.5   proc mergesort m { set len [llength $m] if {$len <= 1} { return $m } set middle [expr {$len / 2}] set left [lrange $m 0 [expr {$middle - 1}]] set right [lrange $m $middle end] return [merge [mergesort $left] [mergesort $right]] }   proc merge {left right} { set result [list] while {[set lleft [llength $left]] > 0 && [set lright [llength $right]] > 0} { if {[lindex $left 0] <= [lindex $right 0]} { set left [lassign $left value] } else { set right [lassign $right value] } lappend result $value } if {$lleft > 0} { lappend result {*}$left } if {$lright > 0} { set result [concat $result $right] ;# another way append elements } return $result }   puts [mergesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9
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.
#Red
Red
  Red []   ;;------------------------------- ;; we have to use function not func here, otherwise we'd have to define all "vars" as local... qsort: function [list][ ;;------------------------------- if 1 >= length? list [ return list ] left: copy [] right: copy [] eq: copy []  ;; "equal" pivot: list/2 ;; simply choose second element as pivot element foreach ele list [ case [ ele < pivot [ append left ele ] ele > pivot [ append right ele ] true [append eq ele ] ] ]  ;; this is the last expression of the function, so coding "return" here is not necessary reduce [qsort left eq qsort right] ]     ;; lets test the function with an array of 100k integers, range 1..1000 list: [] loop 100000 [append list random 1000] t0: now/time/precise  ;; start timestamp qsort list ;; the return value (block) contains the sorted list, original list has not changed print ["time1: " now/time/precise - t0]  ;; about 1.1 sec on my machine t0: now/time/precise sort list  ;; just for fun time the builtin function also ( also implementation of quicksort ) print ["time2: " now/time/precise - t0]  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   cocktail sort   is an improvement on the   Bubble Sort. A cocktail sort is also known as:   cocktail shaker sort   happy hour sort   bidirectional bubble sort   a bubble sort variation   a selection sort variation   ripple sort   shuffle sort   shuttle sort The improvement is basically that values "bubble"   (migrate)   both directions through the array,   because on each iteration the cocktail sort   bubble sorts   once forwards and once backwards. After   ii   passes,   the first   ii   and the last   ii   elements in the array are in their correct positions,   and don't have to be checked (again). By shortening the part of the array that is sorted each time,   the number of comparisons can be halved. Pseudocode for the   2nd   algorithm   (from Wikipedia)   with an added comment and changed indentations: function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check. beginIdx = 1; endIdx = length(A) - 1;   while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end   % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1;   % (FOR (below) decrements the II index by -1.   for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end   % increases `beginIdx` because the elements before `newBeginIdx` are in correct order. beginIdx = newBeginIdx + 1; end end %   indicates a comment,   and   deal   indicates a   swap. Task Implement a   cocktail sort   and optionally show the sorted output here on this page. See the   discussion   page for some timing comparisons. Related task   cocktail sort
#Wren
Wren
import "/fmt" for Fmt import "random" for Random   // translation of pseudo-code var cocktailShakerSort = Fn.new { |a| var begin = 0 var end = a.count - 2 while (begin <= end) { var newBegin = end var newEnd = begin for (i in begin..end) { if (a[i] > a[i+1]) { var t = a[i+1] a[i+1] = a[i] a[i] = t newEnd = i } } end = newEnd - 1 if (end >= begin) { for (i in end..begin) { if (a[i] > a[i+1]) { var t = a[i+1] a[i+1] = a[i] a[i] = t newBegin = i } } } begin = newBegin + 1 } }   // from the RC Cocktail sort task (no optimizations) var cocktailSort = Fn.new { |a| var last = a.count - 1 while (true) { var swapped = false for (i in 0...last) { if (a[i] > a[i+1]) { var t = a[i] a[i] = a[i+1] a[i+1] = t swapped = true } } if (!swapped) return swapped = false if (last >= 1) { for (i in last-1..0) { if (a[i] > a[i+1]) { var t = a[i] a[i] = a[i+1] a[i+1] = t swapped = true } } } if (!swapped) return } }   // First make sure the routines are working correctly. var a = [21, 4, -9, 62, -7, 107, -62, 4, 0, -170] System.print("Original array: %(a)") var b = a.toList // make copy as sorts mutate array in place cocktailSort.call(a) System.print("Cocktail sort : %(a)") cocktailShakerSort.call(b) System.print("C/Shaker sort : %(b)")   // timing comparison code var rand = Random.new() System.print("\nRelative speed of the two sorts") System.print(" N x faster (CSS v CS)") System.print("----- -------------------") var runs = 5 // average over 5 runs say for (n in [1000, 2000, 4000, 8000, 10000, 20000]) { var sum = 0 for (i in 1..runs) { // get 'n' random numbers in range [0, 100,000] // with every other number being negated var nums = List.filled(n, 0) for (i in 0...n) { var rn = rand.int(100000) if (i%2 == 1) rn = -rn nums[i] = rn } // copy the array var nums2 = nums.toList   var start = System.clock cocktailSort.call(nums) var elapsed = System.clock - start var start2 = System.clock cocktailShakerSort.call(nums2) var elapsed2 = System.clock - start2 sum = sum + elapsed/elapsed2 } System.print(" %(Fmt.d(2, (n/1000).floor))k  %(Fmt.f(0, sum/runs, 3))") }
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.
#Tcl
Tcl
package require Tcl 8.5   proc insertionsort {m} { for {set i 1} {$i < [llength $m]} {incr i} { set val [lindex $m $i] set j [expr {$i - 1}] while {$j >= 0 && [lindex $m $j] > $val} { lset m [expr {$j + 1}] [lindex $m $j] incr j -1 } lset m [expr {$j + 1}] $val } return $m }   puts [insertionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#11l
11l
F circle_sort_backend(&A, Int l, r) V n = r - l I n < 2 R 0 V swaps = 0 V m = n I/ 2 L(i) 0 .< m I A[r - (i + 1)] < A[l + i] swap(&A[r - (i + 1)], &A[l + i]) swaps++ I (n [&] 1) != 0 & (A[l + m] < A[l + m - 1]) swap(&A[l + m - 1], &A[l + m]) swaps++ R swaps + circle_sort_backend(&A, l, l + m) + circle_sort_backend(&A, l + m, r)   F circle_sort(&l) V swaps = 0 V s = 1 L s != 0 s = circle_sort_backend(&l, 0, l.len) swaps += s R swaps   L(i) 309 V l = Array(0 .< i) V m = copy(l) random:shuffle(&l) V n = copy(l) circle_sort(&l) I l != m print(l.len) print(n) print(l)
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.
#Unison
Unison
mergeSortBy : (i ->{𝕖} i ->{𝕖} Boolean) ->{𝕖} [i] ->{𝕖} [i] mergeSortBy cmp = merge l1 l2 = match (l1, l2) with (xs, []) -> xs ([], ys) -> ys (x +: xs, y +: ys) -> if cmp x y then x +: merge xs l2 else y +: merge l1 ys ([], []) -> [] cases [] -> [] [x] -> [x] lst -> match halve lst with (left, right) -> merge (mergeSortBy cmp left) (mergeSortBy cmp right)
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.
#REXX
REXX
/*REXX program sorts a stemmed array using the quicksort algorithm. */ call gen@ /*generate the elements for the array. */ call show@ 'before sort' /*show the before array elements. */ call qSort # /*invoke the quicksort subroutine. */ call show@ ' after sort' /*show the after array elements. */ exit /*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 /*──────────────────────────────────────────────────────────────────────────────────────*/ qSort: procedure expose @.; a.1=1; parse arg b.1; $= 1 /*access @.; get @. size; pivot.*/ if inOrder(b.1) then return /*Array already in order? Return*/ do while $\==0; L= a.$; t= b.$; $= $ - 1; if t<2 then iterate H= L + t - 1;  ?= L + t % 2 if @.H<@.L then if @.?<@.H then do; p= @.H; @.H= @.L; end else if @.?>@.L then p= @.L else do; p= @.?; @.?= @.L; end else if @.?<@.L then [email protected] else if @.?>@.H then do; p= @.H; @.H= @.L; end else do; p= @.?; @.?= @.L; end j= L+1; k= h do forever do j=j while j<=k & @.j<=p; end /*a teeny─tiny loop.*/ do k=k by -1 while j< k & @.k>=p; end /*another " " */ if j>=k then leave /*segment finished? */ _= @.j; @.j= @.k; @.k= _ /*swap J&K elements.*/ end /*forever*/ $= $ + 1 k= j - 1; @.L= @.k; @.k= p if j<=? then do; a.$= j; b.$= H-j+1; $= $+1; a.$= L; b.$= k-L; end else do; a.$= L; b.$= k-L; $= $+1; a.$= j; b.$= H-j+1; end end /*while $¬==0*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ show@: w= length(#); do j=1 for #; say 'element' right(j,w) arg(1)":" @.j; end say copies('▒', maxL + w + 22) /*display a separator (between outputs)*/ return /*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ gen@: @.=; maxL=0 /*assign a default value for the array.*/ @.1 = " Rivers that form part of a (USA) state's border " /*this value is adjusted later to include a prefix & suffix.*/ @.2 = '=' /*this value is expanded later. */ @.3 = "Perdido River Alabama, Florida" @.4 = "Chattahoochee River Alabama, Georgia" @.5 = "Tennessee River Alabama, Kentucky, Mississippi, Tennessee" @.6 = "Colorado River Arizona, California, Nevada, Baja California (Mexico)" @.7 = "Mississippi River Arkansas, Illinois, Iowa, Kentucky, Minnesota, Mississippi, Missouri, Tennessee, Louisiana, Wisconsin" @.8 = "St. Francis River Arkansas, Missouri" @.9 = "Poteau River Arkansas, Oklahoma" @.10 = "Arkansas River Arkansas, Oklahoma" @.11 = "Red River (Mississippi watershed) Arkansas, Oklahoma, Texas" @.12 = "Byram River Connecticut, New York" @.13 = "Pawcatuck River Connecticut, Rhode Island and Providence Plantations" @.14 = "Delaware River Delaware, New Jersey, New York, Pennsylvania" @.15 = "Potomac River District of Columbia, Maryland, Virginia, West Virginia" @.16 = "St. Marys River Florida, Georgia" @.17 = "Chattooga River Georgia, South Carolina" @.18 = "Tugaloo River Georgia, South Carolina" @.19 = "Savannah River Georgia, South Carolina" @.20 = "Snake River Idaho, Oregon, Washington" @.21 = "Wabash River Illinois, Indiana" @.22 = "Ohio River Illinois, Indiana, Kentucky, Ohio, West Virginia" @.23 = "Great Miami River (mouth only) Indiana, Ohio" @.24 = "Des Moines River Iowa, Missouri" @.25 = "Big Sioux River Iowa, South Dakota" @.26 = "Missouri River Kansas, Iowa, Missouri, Nebraska, South Dakota" @.27 = "Tug Fork River Kentucky, Virginia, West Virginia" @.28 = "Big Sandy River Kentucky, West Virginia" @.29 = "Pearl River Louisiana, Mississippi" @.30 = "Sabine River Louisiana, Texas" @.31 = "Monument Creek Maine, New Brunswick (Canada)" @.32 = "St. Croix River Maine, New Brunswick (Canada)" @.33 = "Piscataqua River Maine, New Hampshire" @.34 = "St. Francis River Maine, Quebec (Canada)" @.35 = "St. John River Maine, Quebec (Canada)" @.36 = "Pocomoke River Maryland, Virginia" @.37 = "Palmer River Massachusetts, Rhode Island and Providence Plantations" @.38 = "Runnins River Massachusetts, Rhode Island and Providence Plantations" @.39 = "Montreal River Michigan (upper peninsula), Wisconsin" @.40 = "Detroit River Michigan, Ontario (Canada)" @.41 = "St. Clair River Michigan, Ontario (Canada)" @.42 = "St. Marys River Michigan, Ontario (Canada)" @.43 = "Brule River Michigan, Wisconsin" @.44 = "Menominee River Michigan, Wisconsin" @.45 = "Red River of the North Minnesota, North Dakota" @.46 = "Bois de Sioux River Minnesota, North Dakota, South Dakota" @.47 = "Pigeon River Minnesota, Ontario (Canada)" @.48 = "Rainy River Minnesota, Ontario (Canada)" @.49 = "St. Croix River Minnesota, Wisconsin" @.50 = "St. Louis River Minnesota, Wisconsin" @.51 = "Halls Stream New Hampshire, Canada" @.52 = "Salmon Falls River New Hampshire, Maine" @.53 = "Connecticut River New Hampshire, Vermont" @.54 = "Arthur Kill New Jersey, New York (tidal strait)" @.55 = "Kill Van Kull New Jersey, New York (tidal strait)" @.56 = "Hudson River (lower part only) New Jersey, New York" @.57 = "Rio Grande New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila de Zaragoza (Mexico), Chihuahua (Mexico)" @.58 = "Niagara River New York, Ontario (Canada)" @.59 = "St. Lawrence River New York, Ontario (Canada)" @.60 = "Poultney River New York, Vermont" @.61 = "Catawba River North Carolina, South Carolina" @.62 = "Blackwater River North Carolina, Virginia" @.63 = "Columbia River Oregon, Washington" do #=1 until @.#=='' /*find how many entries in array, and */ maxL=max(maxL, length(@.#)) /* also find the maximum width entry.*/ end /*#*/; #= #-1 /*adjust the highest element number. */ @.1= center(@.1, maxL, '-') /* " " header information. */ @.2= copies(@.2, maxL) /* " " " separator. */ return
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.
#TI-83_BASIC
TI-83 BASIC
:"INSERTION" :L1→L2 :0→A :Lbl L :A+1→A :A→B :While B>0 :If L2(B)&leq;L2(B+1) :Goto B :L2(B)→C :L2(B+1)→L2(B) :C→L2(B+1) :B-1→B :End :Lbl B :If A<(dim(L2)-1) :Goto L :DelVar A :DelVar B :DelVar C :Return
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program circleSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" szMessSortBefore: .asciz "Display table before sort.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 #TableNumber: .quad 1,3,6,2,5,9,10,8,4,7 #TableNumber: .quad 1,2,3,4,5,6,7,8,9,10 #TableNumber: .quad 9,5,12,8,2,12,6 TableNumber: .quad 10,9,8,7,6,5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 8 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrszMessSortBefore bl affichageMess ldr x0,qAdrTableNumber // address number table bl displayTable 1: ldr x0,qAdrTableNumber // address number table mov x1,#0 mov x2,#NBELEMENTS -1 // number of élements mov x3,#0 bl circleSort cmp x0,#0 bne 1b ldr x0,qAdrTableNumber // address number table mov x1,#NBELEMENTS // number of élements bl displayTable   ldr x0,qAdrTableNumber // address number table mov x1,#NBELEMENTS // number of élements bl isSorted // control sort cmp x0,#1 // sorted ? beq 2f ldr x0,qAdrszMessSortNok // no !! error sort bl affichageMess b 100f 2: // yes ldr x0,qAdrszMessSortOk bl affichageMess 100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc #0 // perform the system call   qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult qAdrTableNumber: .quad TableNumber qAdrszMessSortOk: .quad szMessSortOk qAdrszMessSortNok: .quad szMessSortNok qAdrszMessSortBefore: .quad szMessSortBefore /******************************************************************/ /* control sorted table */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the number of elements > 0 */ /* x0 return 0 if not sorted 1 if sorted */ isSorted: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers mov x2,#0 ldr x4,[x0,x2,lsl #3] 1: add x2,x2,#1 cmp x2,x1 bge 99f ldr x3,[x0,x2, lsl #3] cmp x3,x4 blt 98f // smaller -> error mov x4,x3 // A[i-1] = A[i] b 1b // else loop 98: mov x0,#0 // error b 100f 99: mov x0,#1 // ok -> return 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* circle sort */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the first index */ /* x2 contains the last index */ /* x3 contains number of swaps */ circleSort: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers stp x8,x9,[sp,-16]! // save registers stp x10,x11,[sp,-16]! // save registers cmp x1,x2 beq 99f mov x7,x0 // save address mov x8,x1 // low mov x9,x2 // high sub x4,x2,x1 lsr x4,x4,#1 mov x10,x4 // mid 1: // start loop cmp x1,x2 bge 3f ldr x5,[x0,x1,lsl #3] ldr x6,[x0,x2,lsl #3] cmp x5,x6 ble 2f str x6,[x0,x1,lsl #3] // swap values str x5,[x0,x2,lsl #3] add x3,x3,#1 2: add x1,x1,#1 // increment lo sub x2,x2,#1 // decrement hi b 1b // and loop 3: cmp x1,x2 // compare lo hi bne 4f // not egal ldr x5,[x0,x1,lsl #3] add x2,x2,#1 ldr x6,[x0,x2,lsl #3] cmp x5,x6 ble 4f str x6,[x0,x1,lsl #3] // swap str x5,[x0,x2,lsl #3] add x3,x3,#1 4: mov x1,x8 // low mov x2,x10 // mid add x2,x2,x1 bl circleSort mov x3,x0 // swaps mov x0,x7 // table address mov x1,x8 // low mov x2,x10 // mid add x1,x2,x1 add x1,x1,#1 mov x2,x9 // high bl circleSort mov x3,x0 // swaps 99: mov x0,x3 // return number swaps 100: ldp x10,x11,[sp],16 // restaur 2 registers ldp x8,x9,[sp],16 // restaur 2 registers ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* Display table elements */ /******************************************************************/ /* x0 contains the address of table */ displayTable: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x2,x0 // table address mov x3,#0 1: // loop display table ldr x0,[x2,x3,lsl #3] ldr x1,qAdrsZoneConv bl conversion10 // décimal conversion ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv // insert conversion bl strInsertAtCharInc bl affichageMess // display message add x3,x3,#1 cmp x3,#NBELEMENTS - 1 ble 1b ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrsZoneConv: .quad sZoneConv /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Action.21
Action!
DEFINE MAX_COUNT="100" INT ARRAY stack(MAX_COUNT) INT stackSize   PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC InitStack() stackSize=0 RETURN   BYTE FUNC IsEmpty() IF stackSize=0 THEN RETURN (1) FI RETURN (0)   PROC Push(INT low,high) stack(stackSize)=low stackSize==+1 stack(stackSize)=high stackSize==+1 RETURN   PROC Pop(INT POINTER low,high) stackSize==-1 high^=stack(stackSize) stackSize==-1 low^=stack(stackSize) RETURN   INT FUNC Partition(INT ARRAY a INT low,high) INT part,v,i,tmp   v=a(high) part=low-1   FOR i=low TO high-1 DO IF a(i)<=v THEN part==+1 tmp=a(part) a(part)=a(i) a(i)=tmp FI OD   part==+1 tmp=a(part) a(part)=a(high) a(high)=tmp RETURN (part)   PROC CircleSort(INT ARRAY a INT size) INT swaps,low,high,lo,hi,tmp,mid   InitStack() DO swaps=0 Push(0,size-1) WHILE IsEmpty()=0 DO Pop(@low,@high) IF low<high THEN lo=low hi=high WHILE lo<hi DO IF a(hi)<a(lo) THEN tmp=a(lo) a(lo)=a(hi) a(hi)=tmp swaps==+1 FI lo==+1 hi==-1 OD IF lo=hi AND a(lo+1)<a(lo) THEN tmp=a(lo) a(lo)=a(lo+1) a(lo+1)=tmp swaps==+1 FI mid=(lo+hi)/2 Push(low,mid) Push(mid+1,high) FI OD UNTIL swaps=0 OD RETURN   PROC Test(INT ARRAY a INT size) PrintE("Array before sort:") PrintArray(a,size) CircleSort(a,size) PrintE("Array after sort:") PrintArray(a,size) PutE() RETURN   PROC Main() INT ARRAY a(10)=[1 4 65535 0 3 7 4 8 20 65530], b(21)=[10 9 8 7 6 5 4 3 2 1 0 65535 65534 65533 65532 65531 65530 65529 65528 65527 65526], c(8)=[101 102 103 104 105 106 107 108], d(12)=[1 65535 1 65535 1 65535 1 65535 1 65535 1 65535]   Test(a,10) Test(b,21) Test(c,8) Test(d,12) RETURN
http://rosettacode.org/wiki/Sorting_algorithms/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.
#UnixPipes
UnixPipes
split() { (while read a b ; do echo $a > $1 ; echo $b > $2 done) }   mergesort() { xargs -n 2 | (read a b; test -n "$b" && ( lc="1.$1" ; gc="2.$1" (echo $a $b;cat)|split >(mergesort $lc >$lc) >( mergesort $gc >$gc) sort -m $lc $gc rm -f $lc $gc; ) || echo $a) }   cat to.sort | mergesort
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.
#Ring
Ring
  # Project : Sorting algorithms/Quicksort   test = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] see "before sort:" + nl showarray(test) quicksort(test, 1, 10) see "after sort:" + nl showarray(test)   func quicksort(a, s, n) if n < 2 return ok t = s + n - 1 l = s r = t p = a[floor((l + r) / 2)] while l <= r while a[l] < p l = l + 1 end while a[r] > p r = r - 1 end if l <= r temp = a[l] a[l] = a[r] a[r] = temp l = l + 1 r = r - 1 ok end if s < r quicksort(a, s, r - s + 1) ok if l < t quicksort(a, l, t - l + 1 ) ok   func showarray(vect) svect = "" for n = 1 to len(vect) svect = svect + vect[n] + " " next svect = left(svect, len(svect) - 1) see svect + nl  
http://rosettacode.org/wiki/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.
#uBasic.2F4tH
uBasic/4tH
PRINT "Insertion sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Insertionsort (n) PROC _ShowArray (n) PRINT   END     _Insertionsort PARAM (1) ' Insertion sort LOCAL (3)   FOR b@ = 1 TO a@-1 c@ = @(b@) d@ = b@ DO WHILE (d@>0) * (c@ < @(ABS(d@-1))) @(d@) = @(d@-1) d@ = d@ - 1 LOOP @(d@) = c@ NEXT 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/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program circleSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" szMessSortBefore: .asciz "Display table before sort.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 #TableNumber: .int 1,3,6,2,5,9,10,8,4,7 #TableNumber: .int 1,2,3,4,5,6,7,8,9,10 TableNumber: .int 9,5,12,8,2,12,6 #TableNumber: .int 10,9,8,7,6,5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 4 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r0,iAdrszMessSortBefore bl affichageMess ldr r0,iAdrTableNumber @ address number table bl displayTable 1: ldr r0,iAdrTableNumber @ address number table mov r1,#0 mov r2,#NBELEMENTS -1 @ number of élements mov r3,#0 bl circleSort cmp r0,#0 bne 1b ldr r0,iAdrTableNumber @ address number table mov r1,#NBELEMENTS @ number of élements bl displayTable   ldr r0,iAdrTableNumber @ address number table mov r1,#NBELEMENTS @ number of élements bl isSorted @ control sort cmp r0,#1 @ sorted ? beq 2f ldr r0,iAdrszMessSortNok @ no !! error sort bl affichageMess b 100f 2: @ yes ldr r0,iAdrszMessSortOk bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrTableNumber: .int TableNumber iAdrszMessSortOk: .int szMessSortOk iAdrszMessSortNok: .int szMessSortNok iAdrszMessSortBefore: .int szMessSortBefore /******************************************************************/ /* control sorted table */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of elements > 0 */ /* r0 return 0 if not sorted 1 if sorted */ isSorted: push {r2-r4,lr} @ save registers mov r2,#0 ldr r4,[r0,r2,lsl #2] 1: add r2,#1 cmp r2,r1 movge r0,#1 bge 100f ldr r3,[r0,r2, lsl #2] cmp r3,r4 movlt r0,#0 blt 100f mov r4,r3 b 1b 100: pop {r2-r4,lr} bx lr @ return /******************************************************************/ /* circle sort */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the first index */ /* r2 contains the last index */ /* r3 contains number of swaps */ circleSort: push {r1-r10,lr} @ save registers cmp r1,r2 beq 99f mov r7,r0 @ save address mov r8,r1 @ low mov r9,r2 @ high sub r4,r2,r1 lsr r4,#1 mov r10,r4 @ mid 1: @ start loop cmp r1,r2 bge 3f ldr r5,[r0,r1,lsl #2] ldr r6,[r0,r2,lsl #2] cmp r5,r6 ble 2f str r6,[r0,r1,lsl #2] @ swap values str r5,[r0,r2,lsl #2] add r3,r3,#1 2: add r1,r1,#1 @ increment lo sub r2,r2,#1 @ decrement hi b 1b @ and loop 3: cmp r1,r2 @ compare lo hi bne 4f @ not egal ldr r5,[r0,r1,lsl #2] add r2,r2,#1 ldr r6,[r0,r2,lsl #2] cmp r5,r6 ble 4f str r6,[r0,r1,lsl #2] @ swap str r5,[r0,r2,lsl #2] add r3,r3,#1 4: mov r1,r8 @ low mov r2,r10 @ mid add r2,r2,r1 bl circleSort mov r3,r0 @ swaps mov r0,r7 @ table address mov r1,r8 @ low mov r2,r10 @ mid add r1,r2,r1 add r1,r1,#1 mov r2,r9 @ high bl circleSort mov r3,r0 @ swaps 99: mov r0,r3 @ return number swaps 100: pop {r1-r10,lr} bx lr @ return   /******************************************************************/ /* Display table elements */ /******************************************************************/ /* r0 contains the address of table */ displayTable: push {r0-r3,lr} @ save registers mov r2,r0 @ table address mov r3,#0 1: @ loop display table ldr r0,[r2,r3,lsl #2] ldr r1,iAdrsZoneConv bl conversion10 @ décimal conversion ldr r0,iAdrsMessResult ldr r1,iAdrsZoneConv @ insert conversion bl strInsertAtCharInc bl affichageMess @ display message add r3,#1 cmp r3,#NBELEMENTS - 1 ble 1b ldr r0,iAdrszCarriageReturn bl affichageMess 100: pop {r0-r3,lr} bx lr iAdrsZoneConv: .int sZoneConv /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"    
http://rosettacode.org/wiki/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.
#Ursala
Ursala
#import std   mergesort "p" = @iNCS :-0 ~&B^?a\~&YaO "p"?abh/~&alh2faltPrXPRC ~&arh2falrtPXPRC   #show+   example = mergesort(lleq) <'zoh','zpb','hhh','egi','bff','cii','yid'>
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.
#Ruby
Ruby
class Array def quick_sort return self if length <= 1 pivot = self[0] less, greatereq = self[1..-1].partition { |x| x < pivot } less.quick_sort + [pivot] + greatereq.quick_sort end end
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Insertion sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#UnixPipes
UnixPipes
selectionsort() { read a test -n "$a" && ( selectionsort | sort -nm <(echo $a) -) }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#AutoHotkey
AutoHotkey
nums := [6, 7, 8, 9, 2, 5, 3, 4, 1] while circlesort(nums, 1, nums.Count(), 0) ; 1-based continue for i, v in nums output .= v ", " MsgBox % "[" Trim(output, ", ") "]" return   circlesort(Arr, lo, hi, swaps){ if (lo = hi) return swaps high:= hi low := lo mid := Floor((hi - lo) / 2) while (lo < hi) { if (Arr[lo] > Arr[hi]){ tempVal := Arr[lo], Arr[lo] := Arr[hi], Arr[hi] := tempVal swaps++ } lo++ hi-- } if (lo = hi) if (Arr[lo] > Arr[hi+1]){ tempVal := Arr[lo], Arr[lo] := Arr[hi+1], Arr[hi+1] := tempVal swaps++ } swaps := circlesort(Arr, low, low+mid, swaps) swaps := circlesort(Arr, low+mid+1, high, swaps) return swaps }
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.
#V
V
[merge [mergei uncons [swap [>] split] dip [[*m] e2 [*a1] b1 a2 : [*m *a1 e2] b1 a2] view].   [a b : [] a b] view [size zero?] [pop concat] [mergei] tailrec].   [msort [splitat [arr a : [arr a take arr a drop]] view i]. [splitarr dup size 2 / >int splitat].   [small?] [] [splitarr] [merge] binrec].
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.
#Run_BASIC
Run BASIC
' ------------------------------- ' quick sort ' ------------------------------- size = 50 dim s(size) ' array to sort for i = 1 to size ' fill it with some random numbers s(i) = rnd(0) * 100 next i   lft = 1 rht = size   [qSort] lftHold = lft rhtHold = rht pivot = s(lft) while lft < rht while (s(rht) >= pivot) and (lft < rht) : rht = rht - 1 :wend if lft <> rht then s(lft) = s(rht) lft = lft + 1 end if while (s(lft) <= pivot) and (lft < rht) : lft = lft + 1 :wend if lft <> rht then s(rht) = s(lft) rht = rht - 1 end if wend   s(lft) = pivot pivot = lft lft = lftHold rht = rhtHold if lft < pivot then rht = pivot - 1 goto [qSort] end if if rht > pivot then lft = pivot + 1 goto [qSort] end if   for i = 1 to size print i;"-->";s(i) next i
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.
#Ursala
Ursala
#import nat   insort = ~&i&& @hNCtX ~&r->lx ^\~&rt nleq-~rlrSPrhlPrSCPTlrShlPNCTPQ@rhPlD
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#C
C
#include <stdio.h>   int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped;   if (start == end) return 0;   // funny "||" on next line is for the center element of odd-lengthed array for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1;   // q == p-1 at this point return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); }   //helper function to show arrays before each call void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf("%d ", x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); }   int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x));   return 0; }
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.
#Vlang
Vlang
fn main() { mut a := [170, 45, 75, -90, -802, 24, 2, 66] println("before: $a") a = merge_sort(a) println("after: $a") }   fn merge_sort(m []int) []int { if m.len <= 1{ return m } else { mid := m.len / 2 mut left := merge_sort(m[..mid]) mut right := merge_sort(m[mid..]) if m[mid-1] <= m[mid] { left << right return left } return merge(mut left, mut right) } }   fn merge(mut left []int,mut right []int) []int { mut result := []int{} for left.len > 0 && right.len > 0 { if left[0] <= right[0]{ result << left[0] left = left[1..] } else { result << right[0] right = right[1..] } } if left.len > 0 { result << left } if right.len > 0 { result << right } return result }
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.
#Rust
Rust
fn main() { println!("Sort numbers in descending order"); let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; println!("Before: {:?}", numbers);   quick_sort(&mut numbers, &|x,y| x > y); println!("After: {:?}\n", numbers);   println!("Sort strings alphabetically"); let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"]; println!("Before: {:?}", strings);   quick_sort(&mut strings, &|x,y| x < y); println!("After: {:?}\n", strings);   println!("Sort strings by length"); println!("Before: {:?}", strings);   quick_sort(&mut strings, &|x,y| x.len() < y.len()); println!("After: {:?}", strings); }   fn quick_sort<T,F>(v: &mut [T], f: &F) where F: Fn(&T,&T) -> bool { let len = v.len(); if len >= 2 { let pivot_index = partition(v, f); quick_sort(&mut v[0..pivot_index], f); quick_sort(&mut v[pivot_index + 1..len], f); } }   fn partition<T,F>(v: &mut [T], f: &F) -> usize where F: Fn(&T,&T) -> bool { let len = v.len(); let pivot_index = len / 2; let last_index = len - 1;   v.swap(pivot_index, last_index);   let mut store_index = 0; for i in 0..last_index { if f(&v[i], &v[last_index]) { v.swap(i, store_index); store_index += 1; } }   v.swap(store_index, len - 1); store_index }
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.
#Vala
Vala
void insertion_sort(int[] array) { var count = 0; for (int i = 1; i < array.length; i++) { var val = array[i]; var j = i; while (j > 0 && val < array[j - 1]) { array[j] = array[j - 1]; j--; } array[j] = val; } }   void main() { int[] array = {4, 65, 2, -31, 0, 99, 2, 83, 782}; insertion_sort(array); foreach (int i in array) print("%d ", i); }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#C.23
C#
using System; using System.Linq;   namespace CircleSort { internal class Program { public static int[] CircleSort(int[] array) { if (array.Length > 0) while (CircleSortR(array, 0, array.Length - 1, 0) != 0) continue; return array; }   private static int CircleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps;   var high = hi; var low = lo; var mid = (hi - lo) / 2;   while (lo < hi) { if (arr[lo] > arr[hi]) { (arr[lo], arr[hi]) = (arr[hi], arr[lo]); numSwaps++; } lo++; hi--; }   if (lo == hi && arr[lo] > arr[hi + 1]) { (arr[lo], arr[hi + 1]) = (arr[hi + 1], arr[lo]); numSwaps++; }   numSwaps = CircleSortR(arr, low, low + mid, numSwaps); numSwaps = CircleSortR(arr, low + mid + 1, high, numSwaps);   return numSwaps; }   private static void Main(string[] args) { var sortedArray = CircleSort(new int[] { 6, 7, 8, 9, 2, 5, 3, 4, 1 }); sortedArray.ToList().ForEach(i => Console.Write(i.ToString() + " ")); Console.WriteLine(); var sortedArray2 = CircleSort(new int[] { 2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1 }); sortedArray2.ToList().ForEach(i => Console.Write(i.ToString() + " ")); Console.WriteLine(); var sortedArray3 = CircleSort(new int[] { 2, 3, 3, 5, 5, 1, 1, 7, 7, 6, 6, 4, 4, 0, 0 }); sortedArray3.ToList().ForEach(i => Console.Write(i.ToString() + " ")); Console.ReadKey(); } } }
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.
#Wren
Wren
var merge = Fn.new { |left, right| var result = [] while (left.count > 0 && right.count > 0) { if (left[0] <= right[0]) { result.add(left[0]) left = left[1..-1] } else { result.add(right[0]) right = right[1..-1] } } if (left.count > 0) result.addAll(left) if (right.count > 0) result.addAll(right) return result }   var mergeSort // recursive mergeSort = Fn.new { |m| var len = m.count if (len <= 1) return m var middle = (len/2).floor var left = m[0...middle] var right = m[middle..-1] left = mergeSort.call(left) right = mergeSort.call(right) if (left[-1] <= right[0]) { left.addAll(right) return left } return merge.call(left, right) }   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)") a = mergeSort.call(a) System.print("After : %(a)") System.print() }
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.
#SASL
SASL
DEF || this rather nice solution is due to Silvio Meira sort () = () sort (a : x) = sort {b <- x; b <= a } ++ a : sort { b <- x; b>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.
#VBA
VBA
Option Base 1 Private Function insertion_sort(s As Variant) As Variant Dim temp As Variant Dim j As Integer For i = 2 To UBound(s) temp = s(i) j = i - 1 Do While s(j) > temp s(j + 1) = s(j) j = j - 1 If j = 0 Then Exit Do Loop s(j + 1) = temp Next i insertion_sort = s End Function   Public Sub main() s = [{4, 15, "delta", 2, -31, 0, "alpha", 19, "gamma", 2, 13, "beta", 782, 1}] Debug.Print "Before: ", Join(s, ", ") Debug.Print "After: ", Join(insertion_sort(s), "' ") End Sub
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#C.2B.2B
C++
#include <iostream>   int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp; swaps++; } lo++; hi--; }   if(lo == hi) { if(arr[lo] > arr[hi+1]) { int temp = arr[lo]; arr[lo] = arr[hi+1]; arr[hi+1] = temp; swaps++; } } swaps = circlesort(arr, low, low+mid, swaps); swaps = circlesort(arr, low+mid+1, high, swaps); return swaps; }   void circlesortDriver(int* arr, int n) { do { for(int i = 0; i < n; i++) { std::cout << arr[i] << ' '; } std::cout << std::endl; } while(circlesort(arr, 0, n-1, 0)); }   int main() { int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 }; circlesortDriver(arr, sizeof(arr)/sizeof(int)); return 0; }
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.
#XPL0
XPL0
code Reserve=3, ChOut=8, IntOut=11;   proc MergeSort(A, Low, High); \Sort array A from Low to High int A, Low, High; int B, Mid, H, I, J, K; [if Low >= High then return; Mid:= (Low+High) >> 1; \split array in half (roughly) MergeSort(A, Low, Mid); \sort left half MergeSort(A, Mid+1, High); \sort right half \Merge the two halves in to sorted order B:= Reserve((High-Low+1)*4); \reserve space for working array (4 bytes/int) H:= Low; I:= Low; J:= Mid+1; while H<=Mid & J<=High do \merge while both halves have items if A(H) <= A(J) then [B(I):= A(H); I:= I+1; H:= H+1] else [B(I):= A(J); I:= I+1; J:= J+1]; if H > Mid then \copy any remaining elements for K:= J to High do [B(I):= A(K); I:= I+1] else for K:= H to Mid do [B(I):= A(K); I:= I+1]; for K:= Low to High do A(K):= B(K); ];   int A, I; [A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; MergeSort(A, 0, 10-1); for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; ]
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.
#Sather
Sather
class SORT{T < $IS_LT{T}} is   private afilter(a:ARRAY{T}, cmp:ROUT{T,T}:BOOL, p:T):ARRAY{T} is filtered ::= #ARRAY{T}; loop v ::= a.elt!; if cmp.call(v, p) then filtered := filtered.append(|v|); end; end; return filtered; end;   private mlt(a, b:T):BOOL is return a < b; end; private mgt(a, b:T):BOOL is return a > b; end; quick_sort(inout a:ARRAY{T}) is if a.size < 2 then return; end; pivot ::= a.median; left:ARRAY{T} := afilter(a, bind(mlt(_,_)), pivot); right:ARRAY{T} := afilter(a, bind(mgt(_,_)), pivot); quick_sort(inout left); quick_sort(inout right); res ::= #ARRAY{T}; res := res.append(left, |pivot|, right); a := res; end; end;
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Insertion sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:   small   n,   as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort. The algorithm is as follows (from wikipedia): function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done Writing the algorithm for integers will suffice.
#VBScript
VBScript
Randomize Dim n(9) 'nine is the upperbound. 'since VBS arrays are 0-based, it will have 10 elements. For L = 0 to 9 n(L) = Int(Rnd * 32768) Next   WScript.StdOut.Write "ORIGINAL : " For L = 0 to 9 WScript.StdOut.Write n(L) & ";" Next   InsertionSort n   WScript.StdOut.Write vbCrLf & " SORTED : " For L = 0 to 9 WScript.StdOut.Write n(L) & ";" Next   'the function Sub InsertionSort(theList) For insertionElementIndex = 1 To UBound(theList) insertionElement = theList(insertionElementIndex) j = insertionElementIndex - 1 Do While j >= 0 'necessary for BASICs without short-circuit evaluation If insertionElement < theList(j) Then theList(j + 1) = theList(j) j = j - 1 Else Exit Do End If Loop theList(j + 1) = insertionElement Next End Sub  
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#CoffeeScript
CoffeeScript
circlesort = (arr, lo, hi, swaps) -> if lo == hi return (swaps)   high = hi low = lo mid = Math.floor((hi-lo)/2)   while lo < hi if arr[lo] > arr[hi] t = arr[lo] arr[lo] = arr[hi] arr[hi] = t swaps++ lo++ hi--   if lo == hi if arr[lo] > arr[hi+1] t = arr[lo] arr[lo] = arr[hi+1] arr[hi+1] = t swaps++   swaps = circlesort(arr,low,low+mid,swaps) swaps = circlesort(arr,low+mid+1,high,swaps)   return(swaps)   VA = [2,14,4,6,8,1,3,5,7,9,10,11,0,13,12,-1]   while circlesort(VA,0,VA.length-1,0) console.log VA
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.
#Yabasic
Yabasic
  dim b(9)   sub copyArray(a(), inicio, final, b()) dim b(final - 1) for k = inicio to final - 1 b(k) = a(k) next end sub   // La mitad izquierda es a(inicio to mitad-1). // La mitad derecha es a(mitad to final-1). // El resultado es b(inicio to final-1). sub topDownMerge(a(), inicio, mitad, final, b()) i = inicio j = mitad   // Si bien hay elementos en los recorridos izquierdo o derecho ... for k = inicio to final - 1 // Si existe un inicio de recorrido izquierdo y es <= inicio de recorrido derecho existente. if (i < mitad) and (j >= final or a(i) <= a(j)) then b(k) = a(i) i = i + 1 else b(k) = a(j) j = j + 1 end if next end sub   // Ordenar la matriz a() usando la matriz b() como fuente. // inicio es inclusivo; final es exclusivo (a(final) no está en el conjunto). sub topDownSplitMerge(b(), inicio, final, a()) if (final - inicio) < 2 then return : fi // Si la diferencia = 1, considérelo ordenado // dividir la ejecución de más de 1 elemento en mitades mitad = int((final + inicio) / 2) // mitad = punto medio // recursively sort both runs from array a() into b() topDownSplitMerge(a(), inicio, mitad, b()) // ordenar la parte izquierda topDownSplitMerge(a(), mitad, final, b()) // ordenar la parte derecha // fusionar las ejecuciones resultantes de la matriz b() en a() topDownMerge(b(), inicio, mitad, final, a()) end sub   // El array a() tiene los elementos para ordenar; array b() es una matriz de trabajo (inicialmente vacía). sub topDownMergeSort(a(), b(), n) copyArray(a(), 0, n, b()) // duplicar la matriz a() en b() topDownSplitMerge(b(), 0, n, a()) // ordenar los datos de b() en a() end sub   sub printArray(a()) for i = 1 to arraysize(a(),1) print a(i) using "####"; next print end sub     //-------------------------- label a1 data 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 label a2 data 7, 5, 2, 6, 1, 4, 2, 6, 3   dim a(9) restore a1 for i = 0 to 9 read p a(i) = p next i   dim a2(8) restore a2 for i = 0 to 8 read p a2(i) = p next i   print "unsort "; printArray(a()) topDownMergeSort (a(), b(), 10) print " sort "; printArray(a()) print print "unsort "; printArray(a2()) topDownMergeSort (a2(), b(), 9) print " sort "; printArray(a2()) end  
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.
#Scala
Scala
def sort(xs: List[Int]): List[Int] = xs match { case Nil => Nil case head :: tail => val (less, notLess) = tail.partition(_ < head) // Arbitrarily partition list in two sort(less) ++ (head :: sort(notLess)) // Sort each half }
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.
#Vlang
Vlang
fn insertion(mut arr []int) { for i in 1 .. arr.len { value := arr[i] mut j := i - 1 for j >= 0 && arr[j] > value { arr[j + 1] = arr[j] j-- } arr[j + 1] = value } }   fn main() { mut arr := [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] println('Input: ' + arr.str()) insertion(mut arr) println('Output: ' + arr.str()) }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#D
D
import std.stdio, std.algorithm, std.array, std.traits;   void circlesort(T)(T[] items) if (isMutable!T) { uint inner(size_t lo, size_t hi, uint swaps) { if (lo == hi) return swaps; auto high = hi; auto low = lo; immutable mid = (hi - lo) / 2;   while (lo < hi) { if (items[lo] > items[hi]) { swap(items[lo], items[hi]); swaps++; } lo++; hi--; }   if (lo == hi && items[lo] > items[hi + 1]) { swap(items[lo], items[hi + 1]); swaps++; } swaps = inner(low, low + mid, swaps); swaps = inner(low + mid + 1, high, swaps); return swaps; }   if (!items.empty) while (inner(0, items.length - 1, 0)) {} }   void main() { import std.random, std.conv;   auto a = [5, -1, 101, -4, 0, 1, 8, 6, 2, 3]; a.circlesort; a.writeln; assert(a.isSorted);   // Fuzzy test. int[30] items; foreach (immutable _; 0 .. 100_000) { auto data = items[0 .. uniform(0, items.length)]; foreach (ref x; data) x = uniform(-items.length.signed * 3, items.length.signed * 3); data.circlesort; assert(data.isSorted); } }
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.
#ZED
ZED
(append) list1 list2 comment: #true (003) "append" list1 list2   (car) pair comment: #true (002) "car" pair   (cdr) pair comment: #true (002) "cdr" pair   (cons) one two comment: #true (003) "cons" one two   (map) function list comment: #true (003) "map" function list   (merge) comparator list1 list2 comment: #true (merge1) comparator list1 list2 nil   (merge1) comparator list1 list2 collect comment: (null?) list2 (append) (reverse) collect list1   (merge1) comparator list1 list2 collect comment: (null?) list1 (append) (reverse) collect list2   (merge1) comparator list1 list2 collect comment: (003) comparator (car) list2 (car) list1 (merge1) comparator list1 (cdr) list2 (cons) (car) list2 collect   (merge1) comparator list1 list2 collect comment: #true (merge1) comparator (cdr) list1 list2 (cons) (car) list1 collect   (null?) value comment: #true (002) "null?" value   (reverse) list comment: #true (002) "reverse" list   (sort) comparator jumble comment: #true (car) (sort11) comparator (sort1) jumble   (sort1) jumble comment: #true (map) "list" jumble   (sort11) comparator jumble comment: (null?) jumble nil   (sort11) comparator jumble comment: (null?) (cdr) jumble jumble   (sort11) comparator jumble comment: #true (sort11) comparator (cons) (merge) comparator (car) jumble (002) "cadr" jumble (sort11) comparator (002) "cddr" jumble
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.
#Scheme
Scheme
(define (split-by l p k) (let loop ((low '()) (high '()) (l l)) (cond ((null? l) (k low high)) ((p (car l)) (loop low (cons (car l) high) (cdr l))) (else (loop (cons (car l) low) high (cdr l))))))   (define (quicksort l gt?) (if (null? l) '() (split-by (cdr l) (lambda (x) (gt? x (car l))) (lambda (low high) (append (quicksort low gt?) (list (car l)) (quicksort high gt?))))))   (quicksort '(1 3 5 7 9 8 6 4 2) >)
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.
#Wren
Wren
var insertionSort = Fn.new { |a| for (i in 1..a.count-1) { var v = a[i] var j = i - 1 while (j >= 0 && a[j] > v) { a[j+1] = a[j] j = j - 1 } a[j+1] = v } }   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)") insertionSort.call(a) System.print("After : %(a)") System.print() }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Delphi
Delphi
  program Sorting_Algorithms;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function CircleSort(a: TArray<Integer>; lo, hi, swaps: Integer): Integer; begin if lo = hi then exit(swaps);   var high := hi; var low := lo; var mid := (hi - lo) div 2;   while lo < hi do begin if a[lo] > a[hi] then begin var tmp := a[lo]; a[lo] := a[hi]; a[hi] := tmp; inc(swaps); end; inc(lo); dec(hi); end;   if lo = hi then begin if a[lo] > a[hi + 1] then begin var tmp := a[lo]; a[lo] := a[hi + 1]; a[hi + 1] := tmp; inc(swaps); end; end; swaps := CircleSort(a, low, low + mid, swaps); swaps := CircleSort(a, low + mid + 1, high, swaps); result := swaps; end;   function ToString(a: TArray<Integer>): string; begin Result := '['; for var e in a do Result := Result + e.ToString + ','; Result := Result + ']'; end;   const aa: TArray<TArray<Integer>> = [[6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]];   begin for var a in aa do begin write('Original: '); write(ToString(a)); while CircleSort(a, 0, high(a), 0) <> 0 do ; writeln; write('Sorted  : '); write(ToString(a)); writeln(#10#10); end; readln; 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.
#zkl
zkl
fcn _merge(left,right){ if (not left) return(right); if (not right) return(left); l:=left[0]; r:=right[0]; if (l<=r) return(L(l).extend(self.fcn(left[1,*],right))); else return(L(r).extend(self.fcn(left,right[1,*]))); }   fcn merge_sort(L){ if (L.len()<2) return(L); n:=L.len()/2; return(_merge(self.fcn(L[0,n]), self.fcn(L[n,*]))); }
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.
#Seed7
Seed7
const proc: quickSort (inout array elemType: arr, in integer: left, in integer: right) is func local var elemType: compare_elem is elemType.value; var integer: less_idx is 0; var integer: greater_idx is 0; var elemType: help is elemType.value; begin if right > left then compare_elem := arr[right]; less_idx := pred(left); greater_idx := right; repeat repeat incr(less_idx); until arr[less_idx] >= compare_elem; repeat decr(greater_idx); until arr[greater_idx] <= compare_elem or greater_idx = left; if less_idx < greater_idx then help := arr[less_idx]; arr[less_idx] := arr[greater_idx]; arr[greater_idx] := help; end if; until less_idx >= greater_idx; arr[right] := arr[less_idx]; arr[less_idx] := compare_elem; quickSort(arr, left, pred(less_idx)); quickSort(arr, succ(less_idx), right); end if; end func;   const proc: quickSort (inout array elemType: arr) is func begin quickSort(arr, 1, length(arr)); end func;
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.
#XPL0
XPL0
code ChOut=8, IntOut=11;   proc InsertionSort(A, L); \Sort array A of length L int A, L; int I, J, V; [for I:= 1 to L-1 do [V:= A(I); J:= I-1; while J>=0 and A(J)>V do [A(J+1):= A(J); J:= J-1; ]; A(J+1):= V; ]; ];   int A, I; [A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; InsertionSort(A, 10); for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; ]
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Elixir
Elixir
defmodule Sort do def circle_sort(data) do List.to_tuple(data) |> circle_sort(0, length(data)-1) |> Tuple.to_list end   defp circle_sort(data, lo, hi) do case circle_sort(data, lo, hi, 0) do {result, 0} -> result {result, _} -> circle_sort(result, lo, hi) end end   defp circle_sort(data, lo, lo, swaps), do: {data, swaps} defp circle_sort(data, lo, hi, swaps) do mid = div(lo + hi, 2) {data, swaps} = do_circle_sort(data, lo, hi, swaps) {data, swaps} = circle_sort(data, lo, mid, swaps) circle_sort(data, mid+1, hi, swaps) end   def do_circle_sort(data, lo, hi, swaps) when lo>=hi do if lo==hi and elem(data, lo) > elem(data, hi+1), do: {swap(data, lo, hi+1), swaps+1}, else: {data, swaps} end def do_circle_sort(data, lo, hi, swaps) do if elem(data, lo) > elem(data, hi), do: do_circle_sort(swap(data, lo, hi), lo+1, hi-1, swaps+1), else: do_circle_sort(data, lo+1, hi-1, swaps) end   defp swap(data, i, j) do vi = elem(data, i) vj = elem(data, j) data |> put_elem(i, vj) |> put_elem(j, vi) end end   data = [6, 7, 8, 9, 2, 5, 3, 4, 1] IO.puts "before sort: #{inspect data}" IO.puts " after sort: #{inspect Sort.circle_sort(data)}"
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Forth
Forth
[UNDEFINED] cell- [IF] : cell- 1 cells - ; [THEN]   defer precedes ( addr addr -- flag ) variable (sorted?) \ is the array sorted?   : (compare) ( a1 a2 -- a1 a2) over @ over @ precedes \ flag if swapped if over over over @ over @ swap rot ! swap ! false (sorted?) ! then ;   : (circlesort) ( a1 a2 --) over over = if drop drop exit then \ quit if indexes are equal over over swap \ swap indexes (end begin) begin over over > \ as long as middle isn't passed while (compare) swap cell- swap cell+ \ check and swap opposite elements repeat rot recurse recurse \ split array and recurse ;   : sort ( a n --) 1- cells over + \ calculate addresses begin true (sorted?) ! over over (circlesort) (sorted?) @ until drop drop ;   :noname < ; is precedes   10 constant /sample create sample 5 , -1 , 101 , -4 , 0 , 1 , 8 , 6 , 2 , 3 ,   : .sample sample /sample cells bounds do i ? 1 cells +loop ;   sample /sample sort .sample
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.
#SETL
SETL
a := [2,5,8,7,0,9,1,3,6,4]; qsort(a); print(a);   proc qsort(rw a); if #a > 1 then pivot := a(#a div 2 + 1); l := 1; r := #a; (while l < r) (while a(l) < pivot) l +:= 1; end; (while a(r) > pivot) r -:= 1; end; swap(a(l), a(r)); end; qsort(a(1..l-1)); qsort(a(r+1..#a)); end if; end proc;   proc swap(rw x, rw y); [y,x] := [x,y]; end proc;
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.
#Yabasic
Yabasic
  sub InsertionSort (matriz()) for i = 1 to arraysize(matriz(),1) valor = matriz(i) j = i - 1 while (j >= 0) and (valor < matriz(j)) matriz(j + 1) = matriz(j) j = j - 1 wend matriz(j + 1) = valor next i end sub   //-------------------------- dim array(10) print "Antes de ordenar:" for i = 1 to 10 array(i) = int(ran(32768)) print array(i), " "; next i print print "\nDespues de ordenar:"   InsertionSort(array())   for i = 1 to 10 print array(i), " "; next i print end  
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Fortran
Fortran
  ! module circlesort ! I have commented the code that was here and also 'tightened up' various pieces such as how swap detection was done as well ! as fixing an error where the code would exceed array bounds for odd number sized arrays. ! Also, giving some some attribution to the author. - Pete ! This code is a Fortran adaptation of a Forth algorithm laid out by "thebeez" at this URL; ! https://sourceforge.net/p/forth-4th/wiki/Circle%20sort/ ! implicit none logical, private :: csr public :: circle_sort   contains   recursive logical function csr(a, left, right,n) result(swapped) implicit none integer, intent(in) :: left, right,n integer, intent(inout) :: a(n) integer :: lo, hi, mid integer :: temp logical :: lefthalf,righthalf ! swapped = .FALSE. if (right <= left) return lo = left !Store the upper and lower bounds of list for hi = right !Recursion later ! do while (lo < hi) ! Swap the pair of elements if hi < lo if (a(hi) < a(lo)) then swapped = .TRUE. temp = a(lo) a(lo) = a(hi) a(hi) = temp endif lo = lo + 1 hi = hi - 1 end do ! Special case if array is an odd size (not even) if (lo == hi)then if(a(hi+1) .lt. a(lo))then swapped = .TRUE. temp = a(hi+1) a(hi+1) = a(lo) a(lo) = temp endif endif mid = (left + right) / 2 ! Bisection point lefthalf = csr(a, left, mid,n) righthalf = csr(a, mid + 1, right,n) swapped = swapped .or. lefthalf .or. righthalf end function csr ! subroutine circle_sort(a, n) use iso_c_binding, only: c_ptr, c_loc implicit none integer, intent(in) :: n integer, target,intent(inout) :: a(n)   do while ( csr(a, 1, n,n)) ! This is the canonical algorithm. However, if you want to ! speed it up, count the iterations and when you have approached ! 0.5*ln(n) iterations, perform a binary insertion sort then exit the loop. end do end subroutine circle_sort   end module circlesort program sort use circlesort implicit none integer :: a(9) data a/6,7,8,9,2,5,3,4,1/ call circle_sort(a, size(a)) print *, a end program sort    
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Quicksort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Sort an array (or list) elements using the   quicksort   algorithm. The elements must have a   strict weak order   and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers. Quicksort, also known as   partition-exchange sort,   uses these steps.   Choose any element of the array to be the pivot.   Divide all other elements (except the pivot) into two partitions.   All elements less than the pivot must be in the first partition.   All elements greater than the pivot must be in the second partition.   Use recursion to sort both partitions.   Join the first sorted partition, the pivot, and the second sorted partition. The best pivot creates partitions of equal length (or lengths differing by   1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The run-time of Quicksort ranges from   O(n log n)   with the best pivots, to   O(n2)   with the worst pivots, where   n   is the number of elements in the array. This is a simple quicksort algorithm, adapted from Wikipedia. function quicksort(array) less, equal, greater := three empty arrays if length(array) > 1 pivot := select any element of array for each x in array if x < pivot then add x to less if x = pivot then add x to equal if x > pivot then add x to greater quicksort(less) quicksort(greater) array := concatenate(less, equal, greater) A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index) Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with   merge sort,   because both sorts have an average time of   O(n log n). "On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
#Sidef
Sidef
func quicksort (a) { a.len < 2 && return(a); var p = a.pop_rand; # to avoid the worst cases __FUNC__(a.grep{ .< p}) + [p] + __FUNC__(a.grep{ .>= p}); }
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.
#Yorick
Yorick
func insertionSort(&A) { for(i = 2; i <= numberof(A); i++) { value = A(i); j = i - 1; while(j >= 1 && A(j) > value) { A(j+1) = A(j); j--; } A(j+1) = value; } }
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#FreeBASIC
FreeBASIC
' version 21-10-2016 ' compile with: fbc -s console ' for boundry checks on array's compile with: fbc -s console -exx ' converted pseudo code into FreeBASIC code   ' shared variables need to be declared before first use Dim Shared As Long cs(-7 To 7)   Function circlesort(lo As Long, hi As Long, swaps As ULong) As ULong   ' array is declared shared ' sort from lower bound to the highter bound ' array's can have subscript range from -2147483648 to +2147483647   If lo = hi Then Return swaps   Dim As Long high = hi Dim As Long low = lo Dim As Long mid_ = (hi - lo) \ 2   While lo < hi If cs(lo) > cs(hi) Then Swap cs(lo), cs(hi) swaps += 1 End If lo += 1 hi -= 1 Wend If lo = hi Then If cs(lo) > cs(hi +1) Then Swap cs(lo), cs(hi +1) swaps += 1 End If End If swaps = circlesort(low , low + mid_, swaps) swaps = circlesort(low + mid_ +1, high, swaps)   Return swaps   End Function   ' ------=< MAIN >=------   Dim As Long i, a = LBound(cs), b = UBound(cs)   Randomize Timer For i = a To b : cs(i) = i  : Next For i = a To b ' little shuffle Swap cs(i), cs(Int(Rnd * (b - a +1)) + a) Next   Print "unsorted "; For i = a To b : Print Using "####"; cs(i); : Next : Print   ' sort the array, loop until sorted While circlesort(a, b, 0) : Wend   Print " sorted "; For i = a To b : Print Using "####"; cs(i); : Next : Print   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Sorting_algorithms/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.
#Simula
Simula
PROCEDURE QUICKSORT(A); REAL ARRAY A; BEGIN   PROCEDURE QS(A, FIRST, LAST); REAL ARRAY A; INTEGER FIRST, LAST; BEGIN INTEGER LEFT, RIGHT; LEFT := FIRST; RIGHT := LAST; IF RIGHT - LEFT + 1 > 1 THEN BEGIN REAL PIVOT; PIVOT := A((LEFT + RIGHT) // 2); WHILE LEFT <= RIGHT DO BEGIN WHILE A(LEFT) < PIVOT DO LEFT := LEFT + 1; WHILE A(RIGHT) > PIVOT DO RIGHT := RIGHT - 1; IF LEFT <= RIGHT THEN BEGIN REAL SWAP; SWAP := A(LEFT); A(LEFT) := A(RIGHT); A(RIGHT) := SWAP; LEFT := LEFT + 1; RIGHT := RIGHT - 1; END; END; QS(A, FIRST, RIGHT); QS(A, LEFT, LAST); END; END QS;   QS(A, LOWERBOUND(A, 1), UPPERBOUND(A, 1));   END QUICKSORT;  
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.
#zkl
zkl
fcn insertionSort(list){ sink:=List(); foreach x in (list){ if(False==(n:=sink.filter1n('>(x)))) sink.append(x); // x>all items in sink else sink.insert(n,x); } sink.close(); }
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#11l
11l
F combsort(&input) V gap = input.len V swaps = 1B L gap > 1 | swaps gap = max(1, Int(gap / 1.25)) swaps = 0B L(i) 0 .< input.len - gap V j = i + gap I input[i] > input[j] swap(&input[i], &input[j]) swaps = 1B   V y = [88, 18, 31, 44, 4, 0, 8, 81, 14, 78, 20, 76, 84, 33, 73, 75, 82, 5, 62, 70] combsort(&y) assert(y == sorted(y)) print(y)
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Before: 6 7 8 9 2 5 3 4 1 After: 1 4 3 5 2 9 8 7 6 Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code: function circlesort (index lo, index hi, swaps) { if lo == hi return (swaps) high := hi low := lo mid := int((hi-lo)/2) while lo < hi { if (value at lo) > (value at hi) { swap.values (lo,hi) swaps++ } lo++ hi-- } if lo == hi if (value at lo) > (value at hi+1) { swap.values (lo,hi+1) swaps++ } swaps := circlesort(low,low+mid,swaps) swaps := circlesort(low+mid+1,high,swaps) return(swaps) } while circlesort (0, sizeof(array)-1, 0) See also For more information on Circle sorting, see Sourceforge.
#Go
Go
package main   import "fmt"   func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circleSort(a, low, low+mid, swaps) swaps = circleSort(a, low+mid+1, high, swaps) return swaps }   func main() { aa := [][]int{ {6, 7, 8, 9, 2, 5, 3, 4, 1}, {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}, } for _, a := range aa { fmt.Printf("Original: %v\n", a) for circleSort(a, 0, len(a)-1, 0) != 0 { // empty block } fmt.Printf("Sorted  : %v\n\n", a) } }