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/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Kotlin
Kotlin
// version 1.1.0   fun countingSort(array: IntArray) { if (array.isEmpty()) return val min = array.min()!! val max = array.max()!! val count = IntArray(max - min + 1) // all elements zero by default for (number in array) count[number - min]++ var z = 0 for (i in min..max) while (count[i - min] > 0) { array[z++] = i count[i - min]-- } }   fun main(args: Array<String>) { val array = intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1) println("Original : ${array.asList()}") countingSort(array) println("Sorted  : ${array.asList()}") }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#BaCon
BaCon
CONST n = 13 FOR x = 1 TO n result$ = APPEND$(result$, 0, STR$(x)) NEXT PRINT SORT$(result$)
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#BBC_BASIC
BBC BASIC
N%=13 PRINT "[" LEFT$(FNLexOrder(0)) "]" END   DEF FNLexOrder(nr%) : LOCAL i%, s$ FOR i%=nr% TO nr% + 9 IF i% > N% EXIT FOR IF i% > 0 s$+=STR$i% + "," + FNLexOrder(i% * 10) NEXT =s$
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#C
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   int compareStrings(const void *a, const void *b) { const char **aa = (const char **)a; const char **bb = (const char **)b; return strcmp(*aa, *bb); }   void lexOrder(int n, int *ints) { char **strs; int i, first = 1, last = n, k = n, len; if (n < 1) { first = n; last = 1; k = 2 - n; } strs = malloc(k * sizeof(char *)); for (i = first; i <= last; ++i) { if (i >= 1) len = (int)log10(i) + 2; else if (i == 0) len = 2; else len = (int)log10(-i) + 3; strs[i-first] = malloc(len); sprintf(strs[i-first], "%d", i); } qsort(strs, k, sizeof(char *), compareStrings); for (i = 0; i < k; ++i) { ints[i] = atoi(strs[i]); free(strs[i]); } free(strs); }   int main() { int i, j, k, n, *ints; int numbers[5] = {0, 5, 13, 21, -22}; printf("In lexicographical order:\n\n"); for (i = 0; i < 5; ++i) { k = n = numbers[i]; if (k < 1) k = 2 - k; ints = malloc(k * sizeof(int)); lexOrder(n, ints); printf("%3d: [", n); for (j = 0; j < k; ++j) { printf("%d ", ints[j]); } printf("\b]\n"); free(ints); } return 0; }
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#C.23
C#
using System; public class Program { public static void Main() { (int x, int y, int z) = (77444, -12, 0);   //Sort directly: if (x > y) (x, y) = (y, x); if (x > z) (x, z) = (z, x); if (y > z) (y, z) = (z, y); Console.WriteLine((x, y, z));   var (a, b, c) = ( "lions, tigers, and", "bears, oh my!", "(from the 'Wizard of OZ')");   //Sort with generic method: Sort(ref a, ref b, ref c); Console.WriteLine((a, b, c)); }   public static void Sort<T>(ref T a, ref T b, ref T c) where T : IComparable<T> { if (a.CompareTo(b) > 0) (a, b) = (b, a); if (a.CompareTo(c) > 0) (a, c) = (c, a); if (b.CompareTo(c) > 0) (b, c) = (c, b); } }
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#C.23
C#
using System; using System.Collections.Generic;   namespace RosettaCode { class SortCustomComparator { // Driver program public void CustomSort() { String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; List<String> list = new List<string>(items);   DisplayList("Unsorted", list);   list.Sort(CustomCompare); DisplayList("Descending Length", list);   list.Sort(); DisplayList("Ascending order", list); }   // Custom compare public int CustomCompare(String x, String y) { int result = -x.Length.CompareTo(y.Length); if (result == 0) { result = x.ToLower().CompareTo(y.ToLower()); }   return result; }   // Output routine public void DisplayList(String header, List<String> theList) { Console.WriteLine(header); Console.WriteLine("".PadLeft(header.Length, '*')); foreach (String str in theList) { Console.WriteLine(str); } Console.WriteLine(); } } }
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Python
Python
'''Sort an outline at every level'''     from itertools import chain, product, takewhile, tee from functools import cmp_to_key, reduce     # ------------- OUTLINE SORTED AT EVERY LEVEL --------------   # sortedOutline :: (Tree String -> Tree String -> Ordering) # -> String # -> Either String String def sortedOutline(cmp): '''Either a message reporting inconsistent indentation, or an outline sorted at every level by the supplied comparator function. ''' def go(outlineText): indentTuples = indentTextPairs( outlineText.splitlines() ) return bindLR( minimumIndent(enumerate(indentTuples)) )(lambda unitIndent: Right( outlineFromForest( unitIndent, nest(foldTree( lambda x: lambda xs: Node(x)( sorted(xs, key=cmp_to_key(cmp)) ) )(Node('')( forestFromIndentLevels( indentLevelsFromLines( unitIndent )(indentTuples) ) ))) ) )) return go     # -------------------------- TEST -------------------------- # main :: IO () def main(): '''Ascending and descending sorts attempted on space-indented and tab-indented outlines, both well-formed and ill-formed. '''   ascending = comparing(root) descending = flip(ascending)   spacedOutline = ''' zeta beta gamma lambda kappa mu delta alpha theta iota epsilon'''   tabbedOutline = ''' zeta beta gamma lambda kappa mu delta alpha theta iota epsilon'''   confusedOutline = ''' alpha epsilon iota theta zeta beta delta gamma kappa lambda mu'''   raggedOutline = ''' zeta beta gamma lambda kappa mu delta alpha theta iota epsilon'''   def displaySort(kcmp): '''Sort function output with labelled comparator for a set of four labelled outlines. ''' k, cmp = kcmp return [ tested(cmp, k, label)( outline ) for (label, outline) in [ ('4-space indented', spacedOutline), ('tab indented', tabbedOutline), ('Unknown 1', confusedOutline), ('Unknown 2', raggedOutline) ] ]   def tested(cmp, cmpName, outlineName): '''Print either message or result. ''' def go(outline): print('\n' + outlineName, cmpName + ':') either(print)(print)( sortedOutline(cmp)(outline) ) return go   # Tests applied to two comparators: ap([ displaySort ])([ ("(A -> Z)", ascending), ("(Z -> A)", descending) ])     # ------------- OUTLINE PARSING AND RENDERING --------------   # forestFromIndentLevels :: [(Int, a)] -> [Tree a] def forestFromIndentLevels(tuples): '''A list of trees derived from a list of values paired with integers giving their levels of indentation. ''' def go(xs): if xs: intIndent, v = xs[0] firstTreeLines, rest = span( lambda x: intIndent < x[0] )(xs[1:]) return [Node(v)(go(firstTreeLines))] + go(rest) else: return [] return go(tuples)     # indentLevelsFromLines :: String -> [(String, String)] # -> [(Int, String)] def indentLevelsFromLines(indentUnit): '''Each input line stripped of leading white space, and tupled with a preceding integer giving its level of indentation from 0 upwards. ''' def go(xs): w = len(indentUnit) return [ (len(x[0]) // w, x[1]) for x in xs ] return go     # indentTextPairs :: [String] -> (String, String) def indentTextPairs(xs): '''A list of (indent, bodyText) pairs.''' def indentAndText(s): pfx = list(takewhile(lambda c: c.isspace(), s)) return (pfx, s[len(pfx):]) return [indentAndText(x) for x in xs]     # outlineFromForest :: String -> [Tree String] -> String def outlineFromForest(tabString, forest): '''An indented outline serialisation of forest, using tabString as the unit of indentation. ''' def go(indent): def serial(node): return [indent + root(node)] + list( concatMap( go(tabString + indent) )(nest(node)) ) return serial return '\n'.join( concatMap(go(''))(forest) )     # --------------- MINIMUM INDENT, OR ANOMALY ---------------   # minimumIndent :: [(Int, [Char])] # -> Either String String def minimumIndent(indexedPrefixes): '''Either a message, if indentation characters are mixed, or indentation widths are inconsistent, or the smallest consistent non-empty indentation. ''' (xs, ts) = tee(indexedPrefixes) (ys, zs) = tee(ts)   def mindentLR(charSet): if list(charSet): def w(x): return len(x[1][0])   unit = min(filter(w, ys), key=w)[1][0] unitWidth = len(unit)   def widthCheck(a, ix): '''Is there a line number at which an anomalous indent width is seen? ''' wx = len(ix[1][0]) return a if (a or 0 == wx) else ( ix[0] if 0 != wx % unitWidth else a ) oddLine = reduce(widthCheck, zs, None) return Left( 'Inconsistent indentation width at line ' + ( str(1 + oddLine) ) ) if oddLine else Right(''.join(unit)) else: return Right('')   def tabSpaceCheck(a, ics): '''Is there a line number at which a variant indent character is used? ''' charSet = a[0].union(set(ics[1][0])) return a if a[1] else ( charSet, ics[0] if 1 < len(charSet) else None )   indentCharSet, mbAnomalyLine = reduce( tabSpaceCheck, xs, (set([]), None) ) return bindLR( Left( 'Mixed indent characters found in line ' + str( 1 + mbAnomalyLine ) ) if mbAnomalyLine else Right(list(indentCharSet)) )(mindentLR)     # ------------------------ GENERIC -------------------------   # Left :: a -> Either a b def Left(x): '''Constructor for an empty Either (option type) value with an associated string. ''' return {'type': 'Either', 'Right': None, 'Left': x}     # Right :: b -> Either a b def Right(x): '''Constructor for a populated Either (option type) value''' return {'type': 'Either', 'Left': None, 'Right': x}     # Node :: a -> [Tree a] -> Tree a def Node(v): '''Constructor for a Tree node which connects a value of some kind to a list of zero or more child trees. ''' return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}     # ap (<*>) :: [(a -> b)] -> [a] -> [b] def ap(fs): '''The application of each of a list of functions, to each of a list of values. ''' def go(xs): return [ f(x) for (f, x) in product(fs, xs) ] return go     # bindLR (>>=) :: Either a -> (a -> Either b) -> Either b def bindLR(m): '''Either monad injection operator. Two computations sequentially composed, with any value produced by the first passed as an argument to the second. ''' def go(mf): return ( mf(m.get('Right')) if None is m.get('Left') else m ) return go     # comparing :: (a -> b) -> (a -> a -> Ordering) def comparing(f): '''An ordering function based on a property accessor f. ''' def go(x, y): fx = f(x) fy = f(y) return -1 if fx < fy else (1 if fx > fy else 0) return go     # concatMap :: (a -> [b]) -> [a] -> [b] def concatMap(f): '''A concatenated list over which a function has been mapped. The list monad can be derived by using a function f which wraps its output in a list, (using an empty list to represent computational failure). ''' def go(xs): return chain.from_iterable(map(f, xs)) return go     # either :: (a -> c) -> (b -> c) -> Either a b -> c def either(fl): '''The application of fl to e if e is a Left value, or the application of fr to e if e is a Right value. ''' return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right'])     # flip :: (a -> b -> c) -> b -> a -> c def flip(f): '''The binary function f with its arguments reversed. ''' return lambda a, b: f(b, a)     # foldTree :: (a -> [b] -> b) -> Tree a -> b def foldTree(f): '''The catamorphism on trees. A summary value defined by a depth-first fold. ''' def go(node): return f(root(node))([ go(x) for x in nest(node) ]) return go     # nest :: Tree a -> [Tree a] def nest(t): '''Accessor function for children of tree node.''' return t.get('nest')     # root :: Tree a -> a def root(t): '''Accessor function for data of tree node.''' return t.get('root')     # span :: (a -> Bool) -> [a] -> ([a], [a]) def span(p): '''The longest (possibly empty) prefix of xs that contains only elements satisfying p, tupled with the remainder of xs. span p xs is equivalent to (takeWhile p xs, dropWhile p xs). ''' def match(ab): b = ab[1] return not b or not p(b[0])   def f(ab): a, b = ab return a + [b[0]], b[1:]   def go(xs): return until(match)(f)(([], xs)) return go     # until :: (a -> Bool) -> (a -> a) -> a -> a def until(p): '''The result of repeatedly applying f until p holds. The initial seed value is x. ''' def go(f): def g(x): v = x while not p(v): v = f(v) return v return g return go     # MAIN --- if __name__ == '__main__': main()
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
#Nim
Nim
proc combSort[T](a: var openarray[T]) = var gap = a.len var swapped = true while gap > 1 or swapped: gap = gap * 10 div 13 if gap == 9 or gap == 10: gap = 11 if gap < 1: gap = 1 swapped = false var i = 0 for j in gap ..< a.len: if a[i] > a[j]: swap a[i], a[j] swapped = true inc i   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] combSort a echo a
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Lua
Lua
function bogosort (list) if type (list) ~= 'table' then return list end   -- Fisher-Yates Knuth shuffle local function shuffle () local rand = math.random(1,#list) for i=1,#list do list[i],list[rand] = list[rand],list[i] rand = math.random(1,#list) end end   -- Returns true only if list is now sorted local function in_order () local last = list[1] for i,v in next,list do if v < last then return false end last = v end return true end   while not in_order() do shuffle() end   return list end
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program bubbleSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessSortOk: .asciz "Table sorted.\n" szMessSortNok: .asciz "Table not sorted !!!!!.\n" sMessResult: .asciz "Value  : @ \n" szCarriageReturn: .asciz "\n"   .align 4 #TableNumber: .int 1,3,6,2,5,9,10,8,4,7 TableNumber: .int 10,9,8,7,6,5,4,3,2,1 .equ NBELEMENTS, (. - TableNumber) / 4 /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   1: ldr r0,iAdrTableNumber @ address number table mov r1,#0 mov r2,#NBELEMENTS @ number of élements bl bubbleSort ldr r0,iAdrTableNumber @ address number table bl displayTable   ldr r0,iAdrTableNumber @ address number table mov r1,#NBELEMENTS @ number of élements bl isSorted @ control sort cmp r0,#1 @ sorted ? beq 2f ldr r0,iAdrszMessSortNok @ no !! error sort bl affichageMess b 100f 2: @ yes ldr r0,iAdrszMessSortOk bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrTableNumber: .int TableNumber iAdrszMessSortOk: .int szMessSortOk iAdrszMessSortNok: .int szMessSortNok /******************************************************************/ /* control sorted table */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the number of elements > 0 */ /* r0 return 0 if not sorted 1 if sorted */ isSorted: push {r2-r4,lr} @ save registers mov r2,#0 ldr r4,[r0,r2,lsl #2] 1: add r2,#1 cmp r2,r1 movge r0,#1 bge 100f ldr r3,[r0,r2, lsl #2] cmp r3,r4 movlt r0,#0 blt 100f mov r4,r3 b 1b 100: pop {r2-r4,lr} bx lr @ return /******************************************************************/ /* bubble sort */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains the first element */ /* r2 contains the number of element */ bubbleSort: push {r1-r9,lr} @ save registers sub r2,r2,#1 @ compute i = n - 1 add r8,r1,#1 1: @ start loop 1 mov r3,r1 @ start index mov r9,#0 sub r7,r2,#1 2: @ start loop 2 add r4,r3,#1 ldr r5,[r0,r3,lsl #2] @ load value A[j] ldr r6,[r0,r4,lsl #2] @ load value A[j+1] cmp r6,r5 @ compare value strlt r6,[r0,r3,lsl #2] @ if smaller inversion strlt r5,[r0,r4,lsl #2] movlt r9,#1 @ top table not sorted add r3,#1 @ increment index j cmp r3,r7 @ end ? ble 2b @ no -> loop 2 cmp r9,#0 @ table sorted ? beq 100f @ yes -> end   sub r2,r2,#1 @ decrement i cmp r2,r8 @ end ? bge 1b @ no -> loop 1   100: pop {r1-r9,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/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Fantom
Fantom
  class Main { Int[] gnomesort (Int[] list) { i := 1 j := 2 while (i < list.size) { if (list[i-1] <= list[i]) { i = j j += 1 } else { list.swap(i-1, i) i -= 1 if (i == 0) { i = j j += 1 } } }   return list }   Void main () { list := [4,1,5,8,2,1,5,7] echo ("" + list + " sorted is " + gnomesort (list)) } }  
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Go
Go
package main   import ( "fmt" "sync" )   var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000   const bead = 'o'   func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) }   func beadSort() { // All space in the abacus = aMax poles x len(a) rows. all := make([]byte, aMax*len(a)) // Slice up space by pole. (The space could be sliced by row instead, // but slicing by pole seemed a more intuitive model of a physical abacus.) abacus := make([][]byte, aMax) for pole, space := 0, all; pole < aMax; pole++ { abacus[pole] = space[:len(a)] space = space[len(a):] } // Use a sync.Waitgroup as the checkpoint mechanism. var wg sync.WaitGroup // Place beads for each number concurrently. (Presumably beads can be // "snapped on" to the middle of a pole without disturbing neighboring // beads.) Also note 'row' here is a row of the abacus. wg.Add(len(a)) for row, n := range a { go func(row, n int) { for pole := 0; pole < n; pole++ { abacus[pole][row] = bead } wg.Done() }(row, n) } wg.Wait() // Now tip the abacus, letting beads fall on each pole concurrently. wg.Add(aMax) for _, pole := range abacus { go func(pole []byte) { // Track the top of the stack of beads that have already fallen. top := 0 for row, space := range pole { if space == bead { // Move each bead individually, but move it from its // starting row to the top of stack in a single operation. // (More physical simulation such as discovering the top // of stack by inspection, or modeling gravity, are // possible, but didn't seem called for by the task. pole[row] = 0 pole[top] = bead top++ } } wg.Done() }(pole) } wg.Wait() // Read out sorted numbers by row. for row := range a { x := 0 for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ { x++ } a[len(a)-1-row] = x } }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Eiffel
Eiffel
    class COCKTAIL_SORT [G -> COMPARABLE]   feature   cocktail_sort (ar: ARRAY [G]): ARRAY [G] -- Array sorted in ascending order. require ar_not_empty: ar.count >= 1 local not_swapped: BOOLEAN sol: ARRAY [G] i, j: INTEGER t: G do create Result.make_empty Result.deep_copy (ar) from until not_swapped = True loop not_swapped := True from i := Result.lower until i = Result.upper - 1 loop if Result [i] > Result [i + 1] then Result := swap (Result, i) not_swapped := False end i := i + 1 end from j := Result.upper - 1 until j = Result.lower loop if Result [j] > Result [j + 1] then Result := swap (Result, j) not_swapped := False end j := j - 1 end end ensure ar_is_sorted: is_sorted (Result) end   feature{NONE}   swap (ar: ARRAY [G]; i: INTEGER): ARRAY [G] -- Array with elements i and i+1 swapped. require ar_not_void: ar /= Void i_is_in_bounds: ar.valid_index (i) local t: G do create Result.make_empty Result.deep_copy (ar) t := Result [i] Result [i] := Result [i + 1] Result [i + 1] := t ensure swapped_right: Result [i + 1] = ar [i] swapped_left: Result [i] = ar [i + 1] end   is_sorted (ar: ARRAY [G]): BOOLEAN --- Is 'ar' sorted in ascending order? require ar_not_empty: ar.is_empty = False local i: INTEGER do Result := True from i := ar.lower until i = ar.upper loop if ar [i] > ar [i + 1] then Result := False end i := i + 1 end end   end    
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#langur
langur
val .countingSort = f(.array) { val .min, .max = minmax(.array) var .count = arr .max-.min+1, 0 for .i in .array { .count[.i-.min+1] += 1 } for .i of .count { _for ~= arr .count[.i], .i+.min-1 } }   val .data = [7, 234, -234, 9, 43, 123, 14]   writeln "Original: ", .data writeln "Sorted  : ", .countingSort(.data)
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Lua
Lua
function CountingSort( f ) local min, max = math.min( unpack(f) ), math.max( unpack(f) ) local count = {} for i = min, max do count[i] = 0 end   for i = 1, #f do count[ f[i] ] = count[ f[i] ] + 1 end   local z = 1 for i = min, max do while count[i] > 0 do f[z] = i z = z + 1 count[i] = count[i] - 1 end end   end     f = { 15, -3, 0, -1, 5, 4, 5, 20, -8 }   CountingSort( f )   for i in next, f do print( f[i] ) end
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#11l
11l
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program stableSort641.s */   /* use merge sort and pointer table */ /* but use a extra table of pointer for the merge */ /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Structures */ /********************************************/ /* city structure */ .struct 0 city_name: // .struct city_name + 8 // string pointer city_country: // .struct city_country + 8 // string pointer city_end:   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Name : @ country : @ \n" szMessSortName: .asciz "Sort table for name of city :\n" szMessSortCountry: .asciz "Sort table for country : \n" szCarriageReturn: .asciz "\n"   // cities name szLondon: .asciz "London" szNewyork: .asciz "New York" szBirmin: .asciz "Birmingham" szParis: .asciz "Paris" // country name szUK: .asciz "UK" szUS: .asciz "US" szFR: .asciz "FR" .align 4 TableCities: e1: .quad szLondon // address name string .quad szUK // address country string e2: .quad szParis .quad szFR e3: .quad szNewyork .quad szUS e4: .quad szBirmin .quad szUK e5: .quad szParis .quad szUS e6: .quad szBirmin .quad szUS /* pointers table */ ptrTableCities: .quad e1 .quad e2 .quad e3 .quad e4 .quad e5 .quad e6 .equ NBELEMENTS, (. - ptrTableCities) / 8   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 ptrTableExtraSort: .skip 8 * NBELEMENTS /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrptrTableCities // address pointers table bl displayTable   ldr x0,qAdrszMessSortName bl affichageMess   ldr x0,qAdrptrTableCities // address pointers table mov x1,0 // not use in routine mov x2,NBELEMENTS - 1 // number of élements mov x3,#city_name // sort by city name mov x4,#'A' // alphanumeric ldr x5,qAdrptrTableExtraSort bl mergeSort ldr x0,qAdrptrTableCities // address table bl displayTable   ldr x0,qAdrszMessSortCountry bl affichageMess   ldr x0,qAdrptrTableCities // address table mov x1,0 // not use in routine mov x2,NBELEMENTS - 1 // number of élements mov x3,#city_country // sort by city country mov x4,#'A' // alphanumeric ldr x5,qAdrptrTableExtraSort bl mergeSort ldr x0,qAdrptrTableCities // address table bl displayTable   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrsZoneConv: .quad sZoneConv qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult qAdrTableCities: .quad TableCities qAdrszMessSortName: .quad szMessSortName qAdrptrTableExtraSort: .quad ptrTableExtraSort qAdrszMessSortCountry: .quad szMessSortCountry qAdrptrTableCities: .quad ptrTableCities /******************************************************************/ /* merge sort */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the index of first element */ /* x2 contains the number of element */ /* x3 contains the offset of area sort */ /* x4 contains the type of area sort N numeric A alpha */ /* x5 contains address extra area */ mergeSort: stp x3,lr,[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 mov x6,x1 // save index first element mov x7,x2 // save number of element mov x11,x0 // save address table cmp x2,x1 // end ? ble 100f add x9,x2,x1 lsr x9,x9,1 // number of element of each subset mov x2,x9 bl mergeSort mov x1,x9 // restaur number of element of each subset add x1,x1,1 mov x2,x7 // restaur number of element bl mergeSort // sort first subset add x10,x9,1 1: sub x1,x10,1 sub x8,x10,1 ldr x2,[x0,x1,lsl 3] str x2,[x5,x8,lsl 3] sub x10,x10,1 cmp x10,x6 bgt 1b mov x10,x9 2: add x1,x10,1 add x8,x7,x9 sub x8,x8,x10 ldr x2,[x0,x1,lsl 3] str x2,[x5,x8,lsl 3] add x10,x10,1 cmp x10,x7 blt 2b   mov x10,x6 //k mov x1,x6 // i mov x2,x7 // j 3: mov x0,x5 // table address x1 = i x2 = j x3 = area sort offeset bl comparArea cmp x0,0 bgt 5f blt 4f // if equal and i < pivot cmp x1,x9 ble 4f // inverse to stable b 5f 4: // store element subset 1 mov x0,x5 ldr x6,[x5,x1, lsl 3] str x6,[x11,x10, lsl 3] add x1,x1,1 b 6f 5: // store element subset 2 mov x0,x5 ldr x6,[x5,x2, lsl 3] str x6,[x11,x10, lsl 3] sub x2,x2,1 6: add x10,x10,1 cmp x10,x7 ble 3b mov x0,x11   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 x3,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* comparison sort area */ /******************************************************************/ /* x0 contains the address of table */ /* x1 indice area sort 1 */ /* x2 indice area sort 2 */ /* x3 contains the offset of area sort */ /* x4 contains the type of area sort N numeric A alpha */ comparArea: 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   ldr x1,[x0,x1,lsl 3] // load pointer element 1 ldr x6,[x1,x3] // load area sort element 1 ldr x2,[x0,x2,lsl 3] // load pointer element 2 ldr x7,[x2,x3] // load area sort element 2 cmp x4,'A' // numeric or alpha ? beq 1f cmp x6,x7 // compare numeric value blt 10f bgt 11f b 12f 1: // else compar alpha string mov x8,#0 2: ldrb w9,[x6,x8] // byte string 1 ldrb w5,[x7,x8] // byte string 2 cmp w9,w5 bgt 11f blt 10f   cmp w9,#0 // end string 1 beq 12f // end comparaison add x8,x8,#1 // else add 1 in counter b 2b // and loop   10: // lower mov x0,-1 b 100f 11: // highter mov x0,1 b 100f 12: // equal mov x0,0 100: 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 stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x2,x0 // table address mov x3,0 1: // loop display table lsl x4,x3,#3 // offset element ldr x6,[x2,x4] // load pointer ldr x1,[x6,city_name] ldr x0,qAdrsMessResult bl strInsertAtCharInc // put name in message ldr x1,[x6,city_country] // and put country in the message bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message add x3,x3,1 cmp x3,#NBELEMENTS blt 1b ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#C.23
C#
using static System.Console; using static System.Linq.Enumerable;   public class Program { public static void Main() { foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}"); }   public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString()); }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector>   void lexicographical_sort(std::vector<int>& numbers) { std::vector<std::string> strings(numbers.size()); std::transform(numbers.begin(), numbers.end(), strings.begin(), [](int i) { return std::to_string(i); }); std::sort(strings.begin(), strings.end()); std::transform(strings.begin(), strings.end(), numbers.begin(), [](const std::string& s) { return std::stoi(s); }); }   std::vector<int> lexicographically_sorted_vector(int n) { std::vector<int> numbers(n >= 1 ? n : 2 - n); std::iota(numbers.begin(), numbers.end(), std::min(1, n)); lexicographical_sort(numbers); return numbers; }   template <typename T> void print_vector(std::ostream& out, const std::vector<T>& v) { out << '['; if (!v.empty()) { auto i = v.begin(); out << *i++; for (; i != v.end(); ++i) out << ',' << *i; } out << "]\n"; }   int main(int argc, char** argv) { for (int i : { 0, 5, 13, 21, -22 }) { std::cout << i << ": "; print_vector(std::cout, lexicographically_sorted_vector(i)); } return 0; }
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <string> #include <vector>   template < class T > void sort3( T& x, T& y, T& z) { std::vector<T> v{x, y, z}; std::sort(v.begin(), v.end()); x = v[0]; y = v[1]; z = v[2]; } int main() { int xi = 77444, yi = -12, zi = 0; sort3( xi, yi, zi ); std::cout << xi << "\n" << yi << "\n" << zi << "\n\n";   std::string xs, ys, zs; xs = "lions, tigers, and"; ys = "bears, oh my!"; zs = "(from the \"Wizard of OZ\")"; sort3( xs, ys, zs ); std::cout << xs << "\n" << ys << "\n" << zs << "\n\n";   float xf = 11.3f, yf = -9.7f, zf = 11.17f; sort3( xf, yf, zf ); std::cout << xf << "\n" << yf << "\n" << zf << "\n\n"; }  
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#C.2B.2B
C++
#include <algorithm> #include <string> #include <cctype>   // compare character case-insensitive struct icompare_char { bool operator()(char c1, char c2) { return std::toupper(c1) < std::toupper(c2); } };   // return true if s1 comes before s2 struct compare { bool operator()(std::string const& s1, std::string const& s2) { if (s1.length() > s2.length()) return true; if (s1.length() < s2.length()) return false; return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), icompare_char()); } };   int main() { std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; std::sort(strings, strings+8, compare()); return 0; }
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Raku
Raku
my @tests = q:to/END/.split( /\n\n+/ )».trim; zeta beta gamma lambda kappa mu delta alpha theta iota epsilon   zeta gamma mu lambda kappa delta beta alpha theta iota epsilon   alpha epsilon iota theta zeta beta delta gamma kappa lambda mu   zeta beta gamma lambda kappa mu delta alpha theta iota epsilon END   for @tests -> $t { say "{'=' x 55}\nUnsorted:\n$t"; my $indent = try detect-indent $t; next unless $indent; say "\nSorted ascending:"; pretty-print import($t, :level($indent) ).List, :ws($indent); say "\nSorted descending:"; pretty-print import($t, :level($indent) ).List, :ws($indent), :desc; }   sub detect-indent ($text) { my $consistent = $text.lines.map(* ~~ / ^ (\h*) /).join.comb.Set; note "\nUnwilling to continue; Inconsistent indent characters." and return '' if +$consistent > 1; my @ws = $text.lines.map: (* ~~ / ^ (\h*) /)».Str; my $indent = @ws.grep( *.chars > 0 ).min.first; note "\nUnwilling to continue; Inconsistent indentation." and return '' unless all @ws.map: { next unless .[0]; (.[0].chars %% $indent.chars) } $indent }   sub import (Str $trees, :$level) { my $forest = '['; my $last = -Inf; for $trees.lines -> $branch { $branch ~~ / ($($level))* /; my $this = +$0; $forest ~= do { given $this cmp $last { when More { (?$this ?? q[ => \[ ] !! "" )~ "'{$branch.trim}'" } when Same { ", '{$branch.trim}'" } when Less { "{']' x $last - $this}, '{$branch.trim}' " } } } $last = $this; } $forest ~= ']' x 1 + $last; use MONKEY-SEE-NO-EVAL; $forest.EVAL; }   multi pretty-print (List $struct, :$level = 0, :$ws = ' ', :$desc = False) { if $desc { pretty-print($_, :level($level), :$ws, :$desc ) for $struct.flat.sort.reverse.List } else { pretty-print($_, :level($level), :$ws, :$desc ) for $struct.flat.sort.List } }   multi pretty-print (Pair $struct, :$level = 0, :$ws = ' ', :$desc = False) { say $ws x $level, $struct.key; pretty-print( $struct.value.sort( ).List, :level($level + 1), :$ws, :$desc ) }   multi pretty-print (Str $struct, :$level = 0, :$ws = ' ', :$desc = False) { say $ws x $level , $struct; }
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
#Objeck
Objeck
  bundle Default { class Stooge { function : Main(args : String[]) ~ Nil { nums := [3, 5, 1, 9, 7, 6, 8, 2, 4]; CombSort(nums); each(i : nums) { IO.Console->Print(nums[i])->Print(","); }; IO.Console->PrintLine(); }   function : CombSort(input : Int[]) ~ Nil { gap : Float := input->Size(); swaps := true; while(gap > 1 | swaps) { gap /= 1.247330950103979; if(gap < 1) { gap := 1; }; i : Int := 0; swaps := false; while(i + gap < input->Size()) { igap : Int := i + gap->As(Int); if (input[i] > input[igap]) { swap : Int := input[i]; input[i] := input[igap]; input[igap] := swap; swaps := true; }; i += 1; }; }; } } }  
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#M4
M4
divert(-1) define(`randSeed',141592653) define(`setRand', `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))') define(`rand_t',`eval(randSeed^(randSeed>>13))') define(`random', `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') define(`set',`define(`$1[$2]',`$3')') define(`new',`set($1,size,0)') define(`get',`defn($1[$2])') define(`append', `set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)') define(`deck', `new($1)for(`x',1,$2, `append(`$1',random)')') define(`show', `for(`x',1,get($1,size),`get($1,x)`'ifelse(x,get($1,size),`',`, ')')') define(`swap',`set($1,$2,get($1,$4))`'set($1,$4,$3)') define(`shuffle', `for(`x',1,get($1,size), `swap($1,x,get($1,x),eval(1+random%get($1,size)))')') define(`inordern', `ifelse(eval($2>=get($1,size)),1, 1, `ifelse(eval(get($1,$2)>get($1,incr($2))),1, 0, `inordern(`$1',incr($2))')')') define(`inorder',`inordern($1,1)') define(`bogosort', `ifelse(inorder(`$1'),0,`nope shuffle(`$1')`'bogosort(`$1')')') divert   deck(`b',6) show(`b') bogosort(`b') show(`b')
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Arturo
Arturo
bubbleSort: function [items][ len: size items loop len [j][ i: 1 while [i =< len-j] [ if items\[i] < items\[i-1] [ tmp: items\[i] items\[i]: items\[i-1] items\[i-1]: tmp ] i: i + 1 ] ] items ]   print bubbleSort [3 1 2 8 5 7 9 4 6]
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Forth
Forth
defer precedes defer exchange   : gnomesort ( a n) swap >r 1 ( n c) begin ( n c) over over > ( n c f) while ( n c) dup if ( n c) dup dup 1- over over r@ precedes if r@ exchange 1- else drop drop 1+ then else 1+ then ( n c) repeat drop drop r> drop ( --) ;   create example 8 93 69 52 50 79 33 52 19 77 , , , , , , , , , ,   :noname >r cells r@ + @ swap cells r> + @ swap < ; is precedes :noname >r cells r@ + swap cells r> + over @ over @ swap rot ! swap ! ; is exchange   : .array 10 0 do example i cells + ? loop cr ;   .array example 10 gnomesort .array
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Groovy
Groovy
def beadSort = { list -> final nPoles = list.max() list.collect { print "." ([true] * it) + ([false] * (nPoles - it)) }.transpose().collect { pole -> print "." pole.findAll { ! it } + pole.findAll { it } }.transpose().collect{ beadTally -> beadTally.findAll{ it }.size() } }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Elena
Elena
import extensions; import system'math; import system'routines;   extension op { cocktailSort() { var list := self.clone();   bool swapped  := true; while(swapped) { swapped := false;   for(int i := 0, i <= list.Length - 2, i += 1) { if (list[i]>list[i+1]) { list.exchange(i,i+1); swapped := true } }; ifnot (swapped) { ^ list }; swapped := false;   for(int i := list.Length - 2, i >= 0, i -= 1) { if (list[i]>list[i+1]) { list.exchange(i,i+1); swapped := true } } };   ^ list } }   public program() { var list := new int[]{3, 5, 1, 9, 7, 6, 8, 2, 4 };   console.printLine("before:", list.asEnumerable()); console.printLine("after :", list.cocktailSort().asEnumerable()) }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#M4
M4
divert(-1)   define(`randSeed',141592653) define(`setRand', `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))') define(`rand_t',`eval(randSeed^(randSeed>>13))') define(`random', `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')   define(`set',`define(`$1[$2]',`$3')') define(`get',`defn(`$1[$2]')') define(`new',`set($1,size,0)') define(`append', `set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)') define(`deck', `new($1)for(`x',1,$2, `append(`$1',eval(random%$3))')') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') define(`show', `for(`x',1,get($1,size),`get($1,x) ')')   define(`countingsort', `for(`x',$2,$3,`set(count,x,0)')`'for(`x',1,get($1,size), `set(count,get($1,x),incr(get(count,get($1,x))))')`'define(`z', 1)`'for(`x',$2,$3, `for(`y',1,get(count,x), `set($1,z,x)`'define(`z',incr(z))')')')   divert deck(`a',10,100) show(`a') countingsort(`a',0,99) show(`a')
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program stableSort641.s */   /* use merge sort and pointer table */ /* but use a extra table of pointer for the merge */ /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Structures */ /********************************************/ /* city structure */ .struct 0 city_name: // .struct city_name + 8 // string pointer city_country: // .struct city_country + 8 // string pointer city_end:   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Name : @ country : @ \n" szMessSortName: .asciz "Sort table for name of city :\n" szMessSortCountry: .asciz "Sort table for country : \n" szCarriageReturn: .asciz "\n"   // cities name szLondon: .asciz "London" szNewyork: .asciz "New York" szBirmin: .asciz "Birmingham" szParis: .asciz "Paris" // country name szUK: .asciz "UK" szUS: .asciz "US" szFR: .asciz "FR" .align 4 TableCities: e1: .quad szLondon // address name string .quad szUK // address country string e2: .quad szParis .quad szFR e3: .quad szNewyork .quad szUS e4: .quad szBirmin .quad szUK e5: .quad szParis .quad szUS e6: .quad szBirmin .quad szUS /* pointers table */ ptrTableCities: .quad e1 .quad e2 .quad e3 .quad e4 .quad e5 .quad e6 .equ NBELEMENTS, (. - ptrTableCities) / 8   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 ptrTableExtraSort: .skip 8 * NBELEMENTS /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrptrTableCities // address pointers table bl displayTable   ldr x0,qAdrszMessSortName bl affichageMess   ldr x0,qAdrptrTableCities // address pointers table mov x1,0 // not use in routine mov x2,NBELEMENTS - 1 // number of élements mov x3,#city_name // sort by city name mov x4,#'A' // alphanumeric ldr x5,qAdrptrTableExtraSort bl mergeSort ldr x0,qAdrptrTableCities // address table bl displayTable   ldr x0,qAdrszMessSortCountry bl affichageMess   ldr x0,qAdrptrTableCities // address table mov x1,0 // not use in routine mov x2,NBELEMENTS - 1 // number of élements mov x3,#city_country // sort by city country mov x4,#'A' // alphanumeric ldr x5,qAdrptrTableExtraSort bl mergeSort ldr x0,qAdrptrTableCities // address table bl displayTable   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrsZoneConv: .quad sZoneConv qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult qAdrTableCities: .quad TableCities qAdrszMessSortName: .quad szMessSortName qAdrptrTableExtraSort: .quad ptrTableExtraSort qAdrszMessSortCountry: .quad szMessSortCountry qAdrptrTableCities: .quad ptrTableCities /******************************************************************/ /* merge sort */ /******************************************************************/ /* x0 contains the address of table */ /* x1 contains the index of first element */ /* x2 contains the number of element */ /* x3 contains the offset of area sort */ /* x4 contains the type of area sort N numeric A alpha */ /* x5 contains address extra area */ mergeSort: stp x3,lr,[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 mov x6,x1 // save index first element mov x7,x2 // save number of element mov x11,x0 // save address table cmp x2,x1 // end ? ble 100f add x9,x2,x1 lsr x9,x9,1 // number of element of each subset mov x2,x9 bl mergeSort mov x1,x9 // restaur number of element of each subset add x1,x1,1 mov x2,x7 // restaur number of element bl mergeSort // sort first subset add x10,x9,1 1: sub x1,x10,1 sub x8,x10,1 ldr x2,[x0,x1,lsl 3] str x2,[x5,x8,lsl 3] sub x10,x10,1 cmp x10,x6 bgt 1b mov x10,x9 2: add x1,x10,1 add x8,x7,x9 sub x8,x8,x10 ldr x2,[x0,x1,lsl 3] str x2,[x5,x8,lsl 3] add x10,x10,1 cmp x10,x7 blt 2b   mov x10,x6 //k mov x1,x6 // i mov x2,x7 // j 3: mov x0,x5 // table address x1 = i x2 = j x3 = area sort offeset bl comparArea cmp x0,0 bgt 5f blt 4f // if equal and i < pivot cmp x1,x9 ble 4f // inverse to stable b 5f 4: // store element subset 1 mov x0,x5 ldr x6,[x5,x1, lsl 3] str x6,[x11,x10, lsl 3] add x1,x1,1 b 6f 5: // store element subset 2 mov x0,x5 ldr x6,[x5,x2, lsl 3] str x6,[x11,x10, lsl 3] sub x2,x2,1 6: add x10,x10,1 cmp x10,x7 ble 3b mov x0,x11   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 x3,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* comparison sort area */ /******************************************************************/ /* x0 contains the address of table */ /* x1 indice area sort 1 */ /* x2 indice area sort 2 */ /* x3 contains the offset of area sort */ /* x4 contains the type of area sort N numeric A alpha */ comparArea: 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   ldr x1,[x0,x1,lsl 3] // load pointer element 1 ldr x6,[x1,x3] // load area sort element 1 ldr x2,[x0,x2,lsl 3] // load pointer element 2 ldr x7,[x2,x3] // load area sort element 2 cmp x4,'A' // numeric or alpha ? beq 1f cmp x6,x7 // compare numeric value blt 10f bgt 11f b 12f 1: // else compar alpha string mov x8,#0 2: ldrb w9,[x6,x8] // byte string 1 ldrb w5,[x7,x8] // byte string 2 cmp w9,w5 bgt 11f blt 10f   cmp w9,#0 // end string 1 beq 12f // end comparaison add x8,x8,#1 // else add 1 in counter b 2b // and loop   10: // lower mov x0,-1 b 100f 11: // highter mov x0,1 b 100f 12: // equal mov x0,0 100: 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 stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers mov x2,x0 // table address mov x3,0 1: // loop display table lsl x4,x3,#3 // offset element ldr x6,[x2,x4] // load pointer ldr x1,[x6,city_name] ldr x0,qAdrsMessResult bl strInsertAtCharInc // put name in message ldr x1,[x6,city_country] // and put country in the message bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message add x3,x3,1 cmp x3,#NBELEMENTS blt 1b ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Ada
Ada
set aTable to "UK London US New York US Birmingham UK Birmingham"   -- -s = stable sort; -t sets the field separator, -k sets the sort "column" range in field numbers. set stableSortedOnColumn2 to (do shell script ("sort -st'" & tab & "' -k2,2 <<<" & quoted form of aTable)) set stableSortedOnColumn1 to (do shell script ("sort -st'" & tab & "' -k1,1 <<<" & quoted form of aTable)) return "Stable sorted on column 2:" & (linefeed & stableSortedOnColumn2) & (linefeed & linefeed & ¬ "Stable sorted on column 1:") & (linefeed & stableSortedOnColumn1)
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#AppleScript
AppleScript
set aTable to "UK London US New York US Birmingham UK Birmingham"   -- -s = stable sort; -t sets the field separator, -k sets the sort "column" range in field numbers. set stableSortedOnColumn2 to (do shell script ("sort -st'" & tab & "' -k2,2 <<<" & quoted form of aTable)) set stableSortedOnColumn1 to (do shell script ("sort -st'" & tab & "' -k1,1 <<<" & quoted form of aTable)) return "Stable sorted on column 2:" & (linefeed & stableSortedOnColumn2) & (linefeed & linefeed & ¬ "Stable sorted on column 1:") & (linefeed & stableSortedOnColumn1)
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Clojure
Clojure
(def n 13) (sort-by str (range 1 (inc n)))
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#COBOL
COBOL
identification division. program-id. LexicographicalNumbers.   data division. working-storage section. 78 MAX-NUMBERS value 21. 77 i pic 9(2). 77 edited-number pic z(2).   01 lex-table. 05 table-itms occurs MAX-NUMBERS. 10 number-lex pic x(2).   procedure division. main. *>-> Load numbers perform varying i from 1 by 1 until i > MAX-NUMBERS move i to edited-number move edited-number to number-lex(i) call "C$JUSTIFY" using number-lex(i), "Left" end-perform   *>-> Sort in lexicographic order sort table-itms ascending number-lex   *>-> Show ordered numbers display "[" no advancing perform varying i from 1 by 1 until i > MAX-NUMBERS display function trim(number-lex(i)) no advancing if i < MAX-NUMBERS display ", " no advancing end-if end-perform display "]" stop run .
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#CLU
CLU
% Sort three variables. % The variables must all be of the same type, and the type % must implement the less-than comparator. sort_three = proc [T: type] (x,y,z: T) returns (T,T,T) where T has lt: proctype (T,T) returns (bool) if y<x then x,y := y,x end if z<y then y,z := z,y end if y<x then x,y := y,z end return(x,y,z) end sort_three   % Test it out on three values, when also given a type and a % formatter. example = proc [T: type] (x,y,z: T, fmt: proctype (T) returns (string)) where T has lt: proctype (T,T) returns (bool) po: stream := stream$primary_output()    % Print the variables stream$putl(po, "x=" || fmt(x) || " y=" || fmt(y) || " z=" || fmt(z))    % Sort them x,y,z := sort_three[T](x,y,z)    % Print them again stream$putl(po, "x=" || fmt(x) || " y=" || fmt(y) || " z=" || fmt(z) || "\n") end example   % And then we also need formatters, since those are not standardized % such as '<' is. fmt_real = proc (n: real) returns (string) return(f_form(n,2,2)) end fmt_real   fmt_str = proc (s: string) returns (string) return( "'" || s || "'" ) end fmt_str   % Test it out on values of each type start_up = proc () example[int] (77444, -12, 0, int$unparse) example[real] (11.3, -9.7, 11.17, fmt_real) example[string] ("lions, tigers and", "bears, oh my!", "(from the \"Wizard of Oz\")", fmt_str) end start_up
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#COBOL
COBOL
program-id. 3var. data division. working-storage section. 1 n binary pic 9(4). 1 num pic -(7)9. 1 a1 pic x(32) value "lions, tigers, and". 1 a2 pic x(32) value "bears, oh my!". 1 a3 pic x(32) value "(from the ""Wizard of OZ"")". 1 n1 pic x(8) value "77444". 1 n2 pic x(8) value "-12". 1 n3 pic x(8) value "0". 1 alpha-table. 2 alpha-entry occurs 3 pic x(32). 1 numeric-table. 2 numeric-entry occurs 3 pic s9(8). 1 filler value "x = y = z = ". 2 lead-in occurs 3 pic x(4). procedure division. begin. move a1 to alpha-entry (1) move a2 to alpha-entry (2) move a3 to alpha-entry (3) sort alpha-entry ascending alpha-entry perform varying n from 1 by 1 until n > 3 display lead-in (n) alpha-entry (n) end-perform   display space   compute numeric-entry (1) = function numval (n1) compute numeric-entry (2) = function numval (n2) compute numeric-entry (3) = function numval (n3) sort numeric-entry ascending numeric-entry perform varying n from 1 by 1 until n > 3 move numeric-entry (n) to num display lead-in (n) num end-perform   stop run . end program 3var.
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Ceylon
Ceylon
shared void run() {   value strings = [ "Cat", "apple", "Adam", "zero", "Xmas", "quit", "Level", "add", "Actor", "base", "butter" ];   value sorted = strings.sort((String x, String y) => if(x.size == y.size) then increasing(x.lowercased, y.lowercased) else decreasing(x.size, y.size));   sorted.each(print); }
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Clean
Clean
import StdEnv   less s1 s2 | size s1 > size s2 = True | size s1 < size s2 = False | otherwise = lower s1 < lower s2 where lower :: String -> String lower s = {toLower c \\ c <-: s}   Start = sortBy less ["This", "is", "a", "set", "of", "strings", "to", "sort"]
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detect and warn of at least two types of inconsistent indentation: inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces) inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces. Your code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units. You should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts. Your sort should not alter the type or size of the indentation units used in the input outline. (For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github). Tests Sort every level of the (4 space indented) outline below lexically, once ascending and once descending. zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Do the same with a tab-indented equivalent of the same outline. zeta gamma mu lambda kappa delta beta alpha theta iota epsilon The output sequence of an ascending lexical sort of each level should be: alpha epsilon iota theta zeta beta delta gamma kappa lambda mu The output sequence of a descending lexical sort of each level should be: zeta gamma mu lambda kappa delta beta alpha theta iota epsilon Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code. alpha epsilon iota theta zeta beta delta gamma kappa lambda mu zeta beta gamma lambda kappa mu delta alpha theta iota epsilon Related tasks   Functional_coverage_tree   Display_an_outline_as_a_nested_table
#Wren
Wren
import "/sort" for Sort import "/fmt" for Fmt   var sortedOutline = Fn.new { |originalOutline, ascending| var outline = originalOutline.toList // make copy in case we mutate it var indent = "" var del = "\x7f" var sep = "\0" var messages = [] if (outline[0].trimStart(" \t") != outline[0]) { System.print(" outline structure is unclear") return } for (i in 1...outline.count) { var line = outline[i] var lc = line.count if (line.startsWith(" ") || line.startsWith(" \t") || line.startsWith("\t")) { var lc2 = line.trimStart(" \t").count var currIndent = line[0...lc-lc2] if (indent == "") { indent = currIndent } else { var correctionNeeded = false if ((currIndent.contains("\t") && !indent.contains("\t")) || (!currIndent.contains("\t") && indent.contains("\t"))) { messages.add(indent + "corrected inconsistent whitespace use at line '%(line)'") correctionNeeded = true } else if (currIndent.count % indent.count != 0) { messages.add(indent + "corrected inconsistent indent width at line '%(line)'") correctionNeeded = true } if (correctionNeeded) { var mult = (currIndent.count / indent.count).round outline[i] = (indent * mult) + line[lc-lc2..-1] } } } } var levels = List.filled(outline.count, 0) levels[0] = 1 var level = 1 var margin = "" while (!levels.all { |l| l > 0 }) { var mc = margin.count for (i in 1...outline.count) { if (levels[i] == 0) { var line = outline[i] if (line.startsWith(margin) && line[mc] != " " && line[mc] != "\t") levels[i] = level } } margin = margin + indent level = level + 1 } var lines = List.filled(outline.count, "") lines[0] = outline[0] var nodes = [] for (i in 1...outline.count) { if (levels[i] > levels[i-1]) { nodes.add((nodes.count == 0) ? outline[i - 1] : sep + outline[i-1]) } else if (levels[i] < levels[i-1]) { var j = levels[i-1] - levels[i] for (k in 1..j) nodes.removeAt(-1) } if (nodes.count > 0) { lines[i] = nodes.join() + sep + outline[i] } else { lines[i] = outline[i] } } if (ascending) { Sort.insertion(lines) } else { var maxLen = lines.reduce(0) { |max, l| (l.count > max) ? l.count : max } for (i in 0...lines.count) lines[i] = Fmt.ljust(maxLen, lines[i], del) Sort.insertion(lines, true) } for (i in 0...lines.count) { var s = lines[i].split(sep) lines[i] = s[-1] if (!ascending) lines[i] = lines[i].trimEnd(del) } if (messages.count > 0) { System.print(messages.join("\n")) System.print() } System.print(lines.join("\n")) }   var outline = [ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon" ]   var outline2 = outline.map { |s| s.replace(" ", "\t") }.toList   var outline3 = [ "alpha", " epsilon", " iota", " theta", "zeta", " beta", " delta", " gamma", " \t kappa", // same length but \t instead of space " lambda", " mu" ]   var outline4 = [ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon" ]   System.print("Four space indented outline, ascending sort:") sortedOutline.call(outline, true)   System.print("\nFour space indented outline, descending sort:") sortedOutline.call(outline, false)   System.print("\nTab indented outline, ascending sort:") sortedOutline.call(outline2, true)   System.print("\nTab indented outline, descending sort:") sortedOutline.call(outline2, false)   System.print("\nFirst unspecified outline, ascending sort:") sortedOutline.call(outline3, true)   System.print("\nFirst unspecified outline, descending sort:") sortedOutline.call(outline3, false)   System.print("\nSecond unspecified outline, ascending sort:") sortedOutline.call(outline4, true)   System.print("\nSecond unspecified outline, descending sort:") sortedOutline.call(outline4, false)
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
#OCaml
OCaml
let comb_sort ~input = let input_length = Array.length input in let gap = ref(input_length) in let swapped = ref true in while (!gap > 1 || !swapped) do if (!gap > 1) then gap := int_of_float (float !gap /. 1.3);   swapped := false; for i = 0 to input_length - !gap do if input.(i) > input.(i + !gap) then begin let tmp = input.(i) in input.(i) <- input.(i + !gap); input.(i + !gap) <- tmp; swapped := true; end done done ;;
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Maple
Maple
arr := Array([2,3,1]): len := numelems(arr): #Translation of C, random swapping shuffle_arr := proc(arr, len) local i, r, temp: for i from 1 to len do temp := arr[i]: r := rand(1..len)(): arr[i] := arr[r]: arr[r] := temp: end do: end proc: while(not ListTools:-Sorted(convert(arr, list))) do shuffle_arr(arr, len): end do: arr;
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#AutoHotkey
AutoHotkey
var = ( dog cat pile abc ) MsgBox % bubblesort(var)   bubblesort(var) ; each line of var is an element of the array { StringSplit, array, var, `n hasChanged = 1 size := array0 While hasChanged { hasChanged = 0 Loop, % (size - 1) { i := array%A_Index% aj := A_Index + 1 j := array%aj% If (j < i) { temp := array%A_Index% array%A_Index% := array%aj% array%aj% := temp hasChanged = 1 } } } Loop, % size sorted .= array%A_Index% . "`n" Return sorted }
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Fortran
Fortran
program example   implicit none   integer :: array(8) = (/ 2, 8, 6, 1, 3, 5, 4, 7 /)   call Gnomesort(array) write(*,*) array   contains   subroutine Gnomesort(a)   integer, intent(in out) :: a(:) integer :: i, j, temp   i = 2 j = 3 do while (i <= size(a)) if (a(i-1) <= a(i)) then i = j j = j + 1 else temp = a(i-1) a(i-1) = a(i) a(i) = temp i = i - 1 if (i == 1) then i = j j = j + 1 end if end if end do   end subroutine Gnomesort   Optimized Version   SUBROUTINE OPTIMIZEDGNOMESORT(A) ! Nice IMPLICIT NONE ! ! Dummy arguments ! REAL , DIMENSION(0:) :: A INTENT (INOUT) A ! ! Local variables ! INTEGER :: posy ! DO posy = 1 , UBOUND(A , 1) !size(a)-1 CALL GNOMESORT(A , posy) END DO RETURN CONTAINS   SUBROUTINE GNOMESORT(A , Upperbound) IMPLICIT NONE ! ! Dummy arguments ! INTEGER :: Upperbound REAL , DIMENSION(0:) :: A INTENT (IN) Upperbound INTENT (INOUT) A ! ! Local variables ! LOGICAL :: eval INTEGER :: posy REAL :: t ! eval = .FALSE. posy = Upperbound eval = (posy>0) .AND. (A(posy - 1)>A(posy)) ! do while ((posy > 0) .and. (a(posy-1) > a(posy))) DO WHILE ( eval ) t = A(posy) A(posy) = A(posy - 1) A(posy - 1) = t ! posy = posy - 1 eval = (posy>0) IF( eval )THEN ! Have to use as a guard condition eval = (A(posy - 1)>A(posy)) ELSE eval = .FALSE. END IF END DO RETURN END SUBROUTINE GNOMESORT   END SUBROUTINE OPTIMIZEDGNOMESORT !   end program example
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Haskell
Haskell
import Data.List   beadSort :: [Int] -> [Int] beadSort = map sum. transpose. transpose. map (flip replicate 1)
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string write("Sorting Demo using ",image(beadsort)) writes(" on list : ") writex(UL := [3, 14, 1, 5, 9, 2, 6, 3]) displaysort(beadsort,copy(UL)) end   procedure beadsort(X) #: return sorted list ascending(or descending) local base,i,j,x # handles negatives and zeros, may also reduce storage   poles := list(max!X-(base := min!X -1),0) # set up poles, we will track sums not individual beads every x := !X do { # each item in the list if integer(x) ~= x then runerr(101,x) # ... must be an integer every poles[1 to x - base] +:= 1 # ... beads "fall" into the sum for that pole }     every (X[j := *X to 1 by -1] := base) & (i := 1 to *poles) do # read from the bottom of the poles if poles[i] > 0 then { # if there's a bead on the pole ... poles[i] -:= 1 # ... remove it X[j] +:= 1 # ... and add it in place } return X end
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Elixir
Elixir
defmodule Sort do def cocktail_sort(list) when is_list(list), do: cocktail_sort(list, [], [])   defp cocktail_sort([], minlist, maxlist), do: Enum.reverse(minlist, maxlist) defp cocktail_sort([x], minlist, maxlist), do: Enum.reverse(minlist, [x | maxlist]) defp cocktail_sort(list, minlist, maxlist) do {max, rev} = cocktail_max(list, []) {min, rest} = cocktail_min(rev, []) cocktail_sort(rest, [min | minlist], [max | maxlist]) end   defp cocktail_max([max], list), do: {max, list} defp cocktail_max([x,y | t], list) when x<y, do: cocktail_max([y | t], [x | list]) defp cocktail_max([x,y | t], list) , do: cocktail_max([x | t], [y | list])   defp cocktail_min([min], list), do: {min, list} defp cocktail_min([x,y | t], list) when x>y, do: cocktail_min([y | t], [x | list]) defp cocktail_min([x,y | t], list) , do: cocktail_min([x | t], [y | list]) end   IO.inspect Sort.cocktail_sort([5,3,9,4,1,6,8,2,7])
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
countingSort[list_] := Module[{minElem, maxElem, count, z, number}, minElem = Min[list]; maxElem = Max[list]; count = ConstantArray[0, (maxElem - minElem + 1)]; For[number = 1, number < Length[list], number++, count[[number - minElem + 1]] = count[[number - minElem + 1]] + 1;] ; z = 1; For[i = minElem, i < maxElem, i++, While[count[[i - minElem + 1]] > 0, list[[z]] = i; z++; count[[i - minElem + 1]] = count[[i - minElem + 1]] - 1;] ]; ]
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#MATLAB_.2F_Octave
MATLAB / Octave
function list = countingSort(list)   minElem = min(list); maxElem = max(list);   count = zeros((maxElem-minElem+1),1);   for number = list count(number - minElem + 1) = count(number - minElem + 1) + 1; end   z = 1;   for i = (minElem:maxElem) while( count(i-minElem +1) > 0) list(z) = i; z = z+1; count(i - minElem + 1) = count(i - minElem + 1) - 1; end end   end %countingSort
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#AutoHotkey
AutoHotkey
Table = ( UK, London US, New York US, Birmingham UK, Birmingham )   Gui, Margin, 6 Gui, -MinimizeBox Gui, Add, ListView, r5 w260 Grid, Orig.Position|Country|City Loop, Parse, Table, `n, `r { StringSplit, out, A_LoopField, `,, %A_Space% LV_Add("", A_Index, out1, out2) } LV_ModifyCol(1, "77 Center") LV_ModifyCol(2, "100 Center") LV_ModifyCol(3, 79) Gui, Add, Button, w80, Restore Order Gui, Add, Button, x+10 wp, Sort Countries Gui, Add, Button, x+10 wp, Sort Cities Gui, Show,, Sort stability Return   GuiClose: GuiEscape: ExitApp   ButtonRestoreOrder: LV_ModifyCol(1, "Sort") Return   ButtonSortCountries: LV_ModifyCol(2, "Sort") Return   ButtonSortCities: LV_ModifyCol(3, "Sort") Return
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#AWK
AWK
  # syntax: GAWK -f SORT_STABILITY.AWK [-v width=x] -v field=x SORT_STABILITY.TXT # # sort by country: GAWK -f SORT_STABILITY.AWK -v field=1 SORT_STABILITY.TXT # sort by city: GAWK -f SORT_STABILITY.AWK -v field=2 SORT_STABILITY.TXT # # awk sort is not stable. Stability may be achieved by appending the # record number, I.E. NR, to each key. # BEGIN { FIELDWIDTHS = "4 20" # 2 fields: country city PROCINFO["sorted_in"] = "@ind_str_asc" if (width == "") { width = 6 } } { arr[$field sprintf("%0*d",width,NR)] = $0 } END { if (length(NR) > width) { printf("error: sort may still be unstable; change width to %d\n",length(NR)) exit(1) } printf("after sorting on field %d:\n",field) for (i in arr) { printf("%s\n",arr[i]) } exit(0) }  
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Common_Lisp
Common Lisp
  (defun lexicographic-sort (n) (sort (alexandria:iota n :start 1) #'string<= :key #'write-to-string)) (lexicographic-sort 13)  
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Factor
Factor
USING: formatting kernel math.parser math.ranges sequences sorting ; IN: rosetta-code.lexicographical-numbers   : lex-order ( n -- seq ) [1,b] [ number>string ] map natural-sort [ string>number ] map ;   { 13 21 -22 } [ dup lex-order "%3d: %[%d, %]\n" printf ] each
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#F.C5.8Drmul.C3.A6
Fōrmulæ
function leq( n as integer, m as integer ) as boolean if str(n)<=str(m) then return true else return false end function   sub shellsort(s() as integer) dim as integer n = ubound(s) dim as integer i, inc = n dim as boolean done   do inc\=2.2 if inc = 0 then inc = 1 do done = false for i = 0 to n - inc if leq(s(i+inc), s(i)) then swap s(i), s(i + inc) done = true end if next loop until done = 0 loop until inc = 1 end sub   dim as integer n, i   input n   dim as integer s(0 to n-1) for i = 0 to n-1 s(i) = i+1 next i   shellsort(s())   print "["; for i = 0 to n-1 print s(i); if i<n-1 then print ", "; next i print "]"
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Cowgol
Cowgol
include "cowgol.coh";   # Sort 3 values sub sort3(a: int32, b: int32, c: int32): (x: int32, y: int32, z: int32) is sub sort2(a: int32, b: int32): (x: int32, y: int32) is if a > b then x := b; y := a; else x := a; y := b; end if; end sub;   x := a; y := b; z := c; (x, y) := sort2(x, y); (x, z) := sort2(x, z); (y, z) := sort2(y, z); end sub;   # Print 3 values sub print3(a: int32, b: int32, c: int32) is sub print1(a: int32) is var buf: uint8[10]; [IToA(a, 10, &buf[0])] := 0; print(&buf[0]); print_char(' '); end sub;   print1(a); print1(b); print1(c); print_nl(); end sub;   var x: int32 := 77444; var y: int32 := -12; var z: int32 := 0;   # Print 3 values before sorting print3(x, y, z);   # Sort 3 values (x, y, z) := sort3(x, y, z);   # Print 3 values after sorting print3(x, y, z);
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#D
D
import std.stdio;   void main() { driver(77444, -12, 0); driver("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")"); }   void driver(T)(T x, T y, T z) { writeln("BEFORE: x=[", x, "]; y=[", y, "]; z=[", z, "]"); sort3Var(x,y,z); writeln("AFTER: x=[", x, "]; y=[", y, "]; z=[", z, "]"); }   void sort3Var(T)(ref T x, ref T y, ref T z) out { assert(x<=y); assert(x<=z); assert(y<=z); } body { import std.algorithm : swap;   if (x < y) { if (z < x) { swap(x,z); } } else if (y < z) { swap(x,y); } else { swap(x,z); } if (z<y) { swap(y,z); } }
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Clojure
Clojure
(defn rosetta-compare [s1 s2] (let [len1 (count s1), len2 (count s2)] (if (= len1 len2) (compare (.toLowerCase s1) (.toLowerCase s2)) (- len2 len1))))   (println (sort rosetta-compare ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]))
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
#Oz
Oz
declare proc {CombSort Arr} Low = {Array.low Arr} High = {Array.high Arr} Size = High - Low + 1 Gap = {NewCell Size} Swapped = {NewCell true} proc {Swap I J} Arr.J := (Arr.I := Arr.J) end in for while:@Gap>1 orelse @Swapped do if @Gap > 1 then Gap := {Float.toInt {Floor {Int.toFloat @Gap} / 1.3}} end Swapped := false for I in Low..High-@Gap do if Arr.I > Arr.(I+@Gap) then {Swap I I+@Gap} Swapped := true end end end end Arr = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)} in {CombSort Arr} {Show {Array.toRecord unit Arr}}
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Bogosort[x_List] := Block[{t=x},While[!OrderedQ[t],t=RandomSample[x]]; t] Bogosort[{1, 2, 6, 4, 0, -1, Pi, 3, 5}] => {-1, 0, 1, 2, 3, Pi, 4, 5, 6}
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#MATLAB_.2F_Octave
MATLAB / Octave
function list = bogoSort(list) while( ~issorted(list) ) %Check to see if it is sorted list = list( randperm(numel(list)) ); %Randomly sort the list end end
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#AWK
AWK
{ # read every line into an array line[NR] = $0 } END { # sort it with bubble sort do { haschanged = 0 for(i=1; i < NR; i++) { if ( line[i] > line[i+1] ) { t = line[i] line[i] = line[i+1] line[i+1] = t haschanged = 1 } } } while ( haschanged == 1 ) # print it for(i=1; i <= NR; i++) { print line[i] } }
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#FreeBASIC
FreeBASIC
' version 21-10-2016 ' compile with: fbc -s console ' for boundry checks on array's compile with: fbc -s console -exx   Sub gnomesort(gnome() As Long) ' sort from lower bound to the highter bound ' array's can have subscript range from -2147483648 to +2147483647 Dim As Long lb = LBound(gnome) Dim As Long ub = UBound(gnome) Dim As Long i = lb +1, j = lb +2   While i < (ub +1) ' replace "<=" with ">=" for downwards sort If gnome(i -1) <= gnome(i) Then i = j j += 1 Else Swap gnome(i -1), gnome(i) i -= 1 If i = lb Then i = j j += 1 End If End If Wend   End Sub   ' ------=< MAIN >=------   Dim As Long i, array(-7 To 7)   Dim As Long a = LBound(array), b = UBound(array)   Randomize Timer For i = a To b : array(i) = i  : Next For i = a To b ' little shuffle Swap array(i), array(Int(Rnd * (b - a +1)) + a) Next   Print "unsort "; For i = a To b : Print Using "####"; array(i); : Next : Print gnomesort(array()) ' sort the array Print " sort "; For i = a To b : Print Using "####"; array(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/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#J
J
bead=: [: +/ #"0&1
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Java
Java
    public class BeadSort { public static void main(String[] args) { BeadSort now=new BeadSort(); int[] arr=new int[(int)(Math.random()*11)+5]; for(int i=0;i<arr.length;i++) arr[i]=(int)(Math.random()*10); System.out.print("Unsorted: "); now.display1D(arr);   int[] sort=now.beadSort(arr); System.out.print("Sorted: "); now.display1D(sort); } int[] beadSort(int[] arr) { int max=a[0]; for(int i=1;i<arr.length;i++) if(arr[i]>max) max=arr[i];   //Set up abacus char[][] grid=new char[arr.length][max]; int[] levelcount=new int[max]; for(int i=0;i<max;i++) { levelcount[i]=0; for(int j=0;j<arr.length;j++) grid[j][i]='_'; } /* display1D(arr); display1D(levelcount); display2D(grid); */   //Drop the beads for(int i=0;i<arr.length;i++) { int num=arr[i]; for(int j=0;num>0;j++) { grid[levelcount[j]++][j]='*'; num--; } } System.out.println(); display2D(grid); //Count the beads int[] sorted=new int[arr.length]; for(int i=0;i<arr.length;i++) { int putt=0; for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++) putt++; sorted[i]=putt; }   return sorted; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display1D(char[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display2D(char[][] arr) { for(int i=0;i<arr.length;i++) display1D(arr[i]); System.out.println(); } }  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Euphoria
Euphoria
function cocktail_sort(sequence s) integer swapped, d object temp sequence fromto fromto = {1,length(s)-1} swapped = 1 d = 1 while swapped do swapped = 0 for i = fromto[(1-d)/2+1] to fromto[(1+d)/2+1] by d do if compare(s[i],s[i+1])>0 then temp = s[i] s[i] = s[i+1] s[i+1] = temp swapped = 1 end if end for d = -d end while return s end function   constant s = rand(repeat(1000,10)) ? s ? cocktail_sort(s)
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#MAXScript
MAXScript
  fn countingSort arr = ( if arr.count < 2 do return arr local minVal = amin arr local maxVal = amax arr local count = for i in 1 to (maxVal-minVal+1) collect 0 for i in arr do ( count[i-minVal+1] = count[i-minVal+1] + 1 ) local z = 1 for i = minVal to maxVal do ( while (count[i-minVal+1]>0) do ( arr[z] = i z += 1 count[i-minVal+1] = count[i-minVal+1] - 1 )   ) return arr )
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Modula-3
Modula-3
MODULE Counting EXPORTS Main;   IMPORT IO, Fmt;   VAR test := ARRAY [1..8] OF INTEGER {80, 10, 40, 60, 50, 30, 20, 70};   PROCEDURE Sort(VAR a: ARRAY OF INTEGER; min, max: INTEGER) = VAR range := max - min + 1; count := NEW(REF ARRAY OF INTEGER, range); z := 0; BEGIN FOR i := FIRST(count^) TO LAST(count^) DO count[i] := 0; END;   FOR i := FIRST(a) TO LAST(a) DO INC(count[a[i] - min]); END;   FOR i := min TO max DO WHILE (count[i - min] > 0) DO a[z] := i; INC(z); DEC(count[i - min]); END; END; END Sort;   BEGIN IO.Put("Unsorted: "); FOR i := FIRST(test) TO LAST(test) DO IO.Put(Fmt.Int(test[i]) & " "); END; IO.Put("\n"); Sort(test, 10, 80); IO.Put("Sorted: "); FOR i := FIRST(test) TO LAST(test) DO IO.Put(Fmt.Int(test[i]) & " "); END; IO.Put("\n"); END Counting.
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#BBC_BASIC
BBC BASIC
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#C
C
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#C.23
C#
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#FreeBASIC
FreeBASIC
function leq( n as integer, m as integer ) as boolean if str(n)<=str(m) then return true else return false end function   sub shellsort(s() as integer) dim as integer n = ubound(s) dim as integer i, inc = n dim as boolean done   do inc\=2.2 if inc = 0 then inc = 1 do done = false for i = 0 to n - inc if leq(s(i+inc), s(i)) then swap s(i), s(i + inc) done = true end if next loop until done = 0 loop until inc = 1 end sub   dim as integer n, i   input n   dim as integer s(0 to n-1) for i = 0 to n-1 s(i) = i+1 next i   shellsort(s())   print "["; for i = 0 to n-1 print s(i); if i<n-1 then print ", "; next i print "]"
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Go
Go
package main   import ( "fmt" "sort" "strconv" )   func lexOrder(n int) []int { first, last, k := 1, n, n if n < 1 { first, last, k = n, 1, 2-n } strs := make([]string, k) for i := first; i <= last; i++ { strs[i-first] = strconv.Itoa(i) } sort.Strings(strs) ints := make([]int, k) for i := 0; i < k; i++ { ints[i], _ = strconv.Atoi(strs[i]) } return ints }   func main() { fmt.Println("In lexicographical order:\n") for _, n := range []int{0, 5, 13, 21, -22} { fmt.Printf("%3d: %v\n", n, lexOrder(n)) } }
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Elena
Elena
import extensions;   sortThree(ref object a, ref object b, ref object c) { if (a > b) { exchange(ref a, ref b) }; if (a > c) { exchange(ref a, ref c) }; if (b > c) { exchange(ref b, ref c) } }   public program() { var x := 5; var y := 1; var z := 2;   var a := "lions, tigers, and"; var b := "bears, oh my!"; var c := "(from the 'Wizard of OZ')";   sortThree(ref x,ref y,ref z); sortThree(ref a,ref b,ref c);   console.printLine(x,",",y,",",z); console.printLine(a,",",b,",",c) }
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Elixir
Elixir
x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")'   [x, y, z] = Enum.sort([x, y, z]) IO.puts "x = #{x}\ny = #{y}\nz = #{z}\n"   x = 77444 y = -12 z = 0   [x, y, z] = Enum.sort([x, y, z]) IO.puts "x = #{x}\ny = #{y}\nz = #{z}"
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Common_Lisp
Common Lisp
CL-USER> (defvar *strings* (list "Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter")) *STRINGS* CL-USER> (sort *strings* #'string-lessp) ("Actor" "Adam" "add" "apple" "base" "butter" "Cat" "Level" "quit" "Xmas" "zero")
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#D
D
import std.stdio, std.string, std.algorithm, std.typecons;   void main() { "here are Some sample strings to be sorted" .split .schwartzSort!q{ tuple(-a.length, a.toUpper) } .writeln; }
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
#PARI.2FGP
PARI/GP
combSort(v)={ my(phi=(1+sqrt(5))/2,magic=1/(1-exp(-phi)),g=#v,swaps); while(g>1 | swaps, if(g>1, g\=magic); swaps=0; for(i=1,#v-g, if(v[i]>v[i+g], my(t=v[i]); v[i]=v[i+g]; v[i+g]=t; swaps++ ) ) ); v };
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#MAXScript
MAXScript
fn notSorted arr = ( if arr.count > 0 then ( local current = arr[1] for i in 2 to arr.count do ( if current > arr[i] then ( return true ) current = arr[i] ) ) false )   fn randSort x y = ( random -1 1 )   fn shuffle arr = ( qsort arr randSort arr )   fn bogosort arr = ( while notSorted arr do ( arr = shuffle arr ) arr )
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Modula-3
Modula-3
MODULE Bogo EXPORTS Main;   IMPORT IO, Fmt, Random;   VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5}; count := 0;   PROCEDURE Shuffle(VAR a: ARRAY OF INTEGER) = VAR temp: INTEGER; BEGIN WITH rand = NEW(Random.Default).init() DO FOR i := FIRST(a) TO LAST(a) - 1 DO WITH j = rand.integer(i, LAST(a)) DO temp := a[i]; a[i] := a[j]; a[j] := temp; END; END; END; END Shuffle;   PROCEDURE Sorted(VAR a: ARRAY OF INTEGER): BOOLEAN = BEGIN IF NUMBER(a) <= 1 THEN RETURN TRUE; END; FOR i := FIRST(a) + 1 TO LAST(a) DO IF (a[i] < a[i - 1]) THEN RETURN FALSE; END; END; RETURN TRUE; END Sorted;   BEGIN Shuffle(a); WHILE NOT Sorted(a) DO Shuffle(a); INC(count); END; FOR i := FIRST(a) TO LAST(a) DO IO.PutInt(a[i]); IO.Put(" "); END; IO.Put("\nRequired " & Fmt.Int(count) & " shuffles\n"); END Bogo.
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#bash
bash
  $ function bubble_sort() { local a=("$@") local n local i local j local t ft=(false true) n=${#a[@]} # array length i=n while ${ft[$(( 0 < i ))]} do j=0 while ${ft[$(( j+1 < i ))]} do if ${ft[$(( a[j+1] < a[j] ))]} then t=${a[j+1]} a[j+1]=${a[j]} a[j]=$t fi t=$(( ++j )) done t=$(( --i )) done echo ${a[@]} }   > > > > > > > > > > > > > > > > > > > > > > > > > $ # this line output from bash $ bubble_sort 3 2 8 2 3 8 $ # create an array variable $ a=(2 45 83 89 1 82 69 88 112 99 0 82 58 65 782 74 -31 104 4 2) $ bubble_sort ${a[@]} -31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782 $ b=($( bubble_sort ${a[@]} ) ) $ echo ${#b[@]} 20 $ echo ${b[@]} -31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782 $  
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Gambas
Gambas
Public Sub Main() Dim siCount As Short Dim siCounti As Short = 1 Dim siCountj As Short = 2 Dim siToSort As Short[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24]   Print "To sort: - "; GoSub Display   While siCounti < siToSort.Count If siToSort[siCounti - 1] <= siToSort[siCounti] Then siCounti = siCountj Inc siCountj Else Swap siToSort[siCounti - 1], siToSort[siCounti] Dec siCounti If siCounti = 0 Then siCounti = siCountj Inc siCountj Endif Endif Wend   Print "Sorted: - "; GoSub Display   Return '-------------------------------------------- Display:   For siCount = 0 To siToSort.Max Print Format(Str(siToSort[siCount]), "####"); If siCount <> siToSort.max Then Print ","; Next   Print Return   End
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#jq
jq
# ncols is the number of columns (i.e. vertical poles) def column_sums(ncols): . as $abacus | reduce range(0; ncols) as $col ([]; . + [reduce $abacus[] as $row (0; if $row > $col then .+1 else . end)]) ;
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Factor
Factor
USING: kernel locals math math.ranges sequences ;   :: cocktail-sort! ( seq -- seq' ) f :> swapped!  ! bind false to mutable lexical variable 'swapped'. This must be done outside both while quotations so it is in scope of both. [ swapped ] [  ! is swapped true? Then execute body quotation. 'do' executes body quotation before predicate on first pass. f swapped!  ! set swapped to false seq length 2 - [| i |  ! for each i in 0 to seq length - 2 do i i 1 + [ seq nth ] bi@ >  ! is element at index i greater than element at index i + 1? [ i i 1 + seq exchange t swapped! ] when  ! if so, swap them and set swapped to true ] each-integer swapped [  ! skip to end of loop if swapped is false seq length 2 - 0 [a,b] [| i |  ! for each i in seq length - 2 to 0 do i i 1 + [ seq nth ] bi@ >  ! is element at index i greater than element at index i + 1? [ i i 1 + seq exchange t swapped! ] when  ! if so, swap them and set swapped to true ] each ] when ] do while seq ;  ! return the sequence
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Nanoquery
Nanoquery
def countingSort(array, min, max) count = {0} * (max - min + 1)   for number in array count[number - min] += 1 end   z = 0 for i in range(min, max) while count[i - min] > 0 array[z] = i z += 1 count[i - min] -= 1; end end end
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#11l
11l
F sort_disjoint_sublist(&data, indices) V sindices = sorted(indices) V values = sorted(sindices.map(i -> @data[i])) L(index, value) zip(sindices, values) data[index] = value   V d = [7, 6, 5, 4, 3, 2, 1, 0] V i = [6, 1, 7] sort_disjoint_sublist(&d, i) print(d)
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#C.2B.2B
C++
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Clojure
Clojure
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Haskell
Haskell
import Data.List (sort)   task :: (Ord b, Show b) => [b] -> [b] task = map snd . sort . map (\i -> (show i, i))   main = print $ task [1 .. 13]
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#F.23
F#
let x = "lions, tigers, and" let y = "bears, oh my!" let z = """(from the "Wizard of OZ")""" List.iter (printfn "%s") (List.sort [x;y;z])  
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Delphi
Delphi
program SortWithCustomComparator;   {$APPTYPE CONSOLE}   uses SysUtils, Types, Generics.Collections, Generics.Defaults;   var lArray: TStringDynArray; begin lArray := TStringDynArray.Create('Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted');   TArray.Sort<string>(lArray , TDelegatedComparer<string>.Construct( function(const Left, Right: string): Integer begin //Returns ('Here', 'are', 'be', 'sample', 'some', 'sorted', 'strings', 'to') //Result := CompareStr(Left, Right);   //Returns ('are', 'be', 'Here', 'sample', 'some', 'sorted', 'strings', 'to') Result := CompareText(Left, Right); end)); end.
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Pascal
Pascal
program CombSortDemo;     // NOTE: The array is 1-based // If you want to use this code on a 0-based array, see below type TIntArray = array[1..40] of integer;   var data: TIntArray; i: integer;   procedure combSort(var a: TIntArray); var i, gap, temp: integer; swapped: boolean; begin gap := length(a); swapped := true; while (gap > 1) or swapped do begin gap := trunc(gap / 1.3); if (gap < 1) then gap := 1; swapped := false; for i := 1 to length(a) - gap do if a[i] > a[i+gap] then begin temp := a[i]; a[i] := a[i+gap]; a[i+gap] := temp; swapped := true; end; end; end;   begin Randomize; writeln('The data before sorting:'); for i := low(data) to high(data) do begin data[i] := Random(high(data)); write(data[i]:4); end; writeln; combSort(data); writeln('The data after sorting:'); for i := low(data) to high(data) do begin write(data[i]:4); end; writeln; end.
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Nanoquery
Nanoquery
def sorted(list) if len(list) = 0 return true end   for i in range(0, len(list) - 2) if list[i] > list[i + 1] return false end end   return true end   def bogosort(list) while not sorted(list) list = list.shuffle() end   return list end
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#BASIC
BASIC
  DO changed = 0 FOR I = 1 TO size -1 IF nums(I) > nums(I + 1) THEN tmp = nums(I) nums(I) = nums(I + 1) nums(I + 1) = tmp changed = 1 END IF NEXT LOOP WHILE(NOT changed)
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Go
Go
package main   import "fmt"   func main() { a := []int{170, 45, 75, -90, -802, 24, 2, 66} fmt.Println("before:", a) gnomeSort(a) fmt.Println("after: ", a) }   func gnomeSort(a []int) { for i, j := 1, 2; i < len(a); { if a[i-1] > a[i] { a[i-1], a[i] = a[i], a[i-1] i-- if i > 0 { continue } } i = j j++ } }
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Julia
Julia
function beadsort(a::Vector{<:Integer}) lo, hi = extrema(a) if lo < 1 throw(DomainError()) end len = length(a) abacus = falses(len, hi) for (i, v) in enumerate(a) abacus[i, 1:v] = true end for i in 1:hi v = sum(abacus[:, i]) if v < len abacus[1:end-v, i] = false abacus[end-v+1:end, i] = true end end return collect(eltype(a), sum(abacus[i,:]) for i in 1:len) end   v = rand(UInt8, 20) println("# unsorted bytes: $v\n -> sorted bytes: $(beadsort(v))") v = rand(1:2 ^ 10, 20) println("# unsorted integers: $v\n -> sorted integers: $(beadsort(v))")
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Kotlin
Kotlin
// version 1.1.2   fun beadSort(a: IntArray) { val n = a.size if (n < 2) return var max = a.max()!! val beads = ByteArray(max * n) /* mark the beads */ for (i in 0 until n) for (j in 0 until a[i]) beads[i * max + j] = 1   for (j in 0 until max) { /* count how many beads are on each post */ var sum = 0 for (i in 0 until n) { sum += beads[i * max + j] beads[i * max + j] = 0 } /* mark bottom sum beads */ for (i in n - sum until n) beads[i * max + j] = 1 }   for (i in 0 until n) { var j = 0 while (j < max && beads[i * max + j] == 1.toByte()) j++ a[i] = j } }   fun main(args: Array<String>) { val a = intArrayOf(5, 3, 1, 7, 4, 1, 1, 20) println("Before sorting : ${a.contentToString()}") beadSort(a) println("After sorting  : ${a.contentToString()}") }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Forth
Forth
defer precedes ( addr addr -- flag ) \ e.g. ' < is precedes : sort ( a n --) 1- cells bounds 2>r false begin 0= dup while 2r@ ?do i cell+ @ i @ over over precedes ( mark unsorted ) if i cell+ ! i ! dup xor else drop drop then 1 cells +loop 0= dup while 2r@ swap 1 cells - ?do i cell+ @ i @ over over precedes ( mark unsorted ) if i cell+ ! i ! dup xor else drop drop then -1 cells +loop repeat then drop 2r> 2drop ;
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Counting sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.util.List   icounts = [int - 1, 3, 6, 2, 7, 13, 20, 12, 21, 11 - , 22, 10, 23, 9, 24, 8, 25, 43, 62, 42 - , 63, 41, 18, 42, 17, 43, 16, 44, 15, 45 - , 14, 46, 79, 113, 78, 114, 77, 39, 78, 38 - ] scounts = int[icounts.length]   System.arraycopy(icounts, 0, scounts, 0, icounts.length) lists = [ - icounts - , countingSort(scounts) - ]   loop ln = 0 to lists.length - 1 cl = lists[ln] rep = Rexx('') loop ct = 0 to cl.length - 1 rep = rep cl[ct] end ct say '['rep.strip.changestr(' ', ',')']' end ln   return   method getMin(array = int[]) public constant binary returns int   amin = Integer.MAX_VALUE loop x_ = 0 to array.length - 1 if array[x_] < amin then amin = array[x_] end x_   return amin   method getMax(array = int[]) public constant binary returns int   amax = Integer.MIN_VALUE loop x_ = 0 to array.length - 1 if array[x_] > amax then amax = array[x_] end x_   return amax   method countingSort(array = int[], amin = getMin(array), amax = getMax(array)) public constant binary returns int[]   count = int[amax - amin + 1] loop nr = 0 to array.length - 1 numbr = array[nr] count[numbr - amin] = count[numbr - amin] + 1 end nr   z_ = 0   loop i_ = amin to amax loop label count while count[i_ - amin] > 0 array[z_] = i_ z_ = z_ + 1 count[i_ - amin] = count[i_ - amin] - 1 end count end i_   return array  
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   BYTE FUNC InSet(INT ARRAY s INT size INT v) INT i   FOR i=0 TO size-1 DO IF s(i)=v THEN RETURN (1) FI OD RETURN (0)   PROC Sort(INT ARRAY arr INT arrSize INT ARRAY ind INT indSize) INT i,j,minpos,tmp   FOR i=0 TO arrSize-2 DO IF InSet(ind,indSize,i) THEN minpos=i FOR j=i+1 TO arrSize-1 DO IF InSet(ind,indSize,j)=1 AND arr(minpos)>arr(j) THEN minpos=j FI OD   IF minpos#i THEN tmp=arr(i) arr(i)=arr(minpos) arr(minpos)=tmp FI FI OD RETURN   PROC Test(INT ARRAY arr INT arrSize INT ARRAY ind INT indSize) PrintE("Array before sort:") PrintArray(arr,arrSize) PrintE("Indices:") PrintArray(ind,indSize) Sort(arr,arrSize,ind,indSize) PrintE("Array after sort:") PrintArray(arr,arrSize) RETURN   PROC Main() INT ARRAY arr(8)=[7 6 5 4 3 2 1 0], ind(3)=[6 1 7]   Test(arr,8,ind,3) RETURN
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#Ada
Ada
with Ada.Text_IO, GNAT.Bubble_Sort; use Ada.Text_IO;   procedure DisjointSort is   package Int_Io is new Integer_IO (Integer);   subtype Index_Range is Natural range 1 .. 8; Input_Array : array (Index_Range) of Integer := (7, 6, 5, 4, 3, 2, 1, 0);   subtype Subindex_Range is Natural range 1 .. 3; type Sub_Arrays is array (Subindex_Range) of Integer;   Sub_Index : Sub_Arrays := (7, 2, 8); Sub_Array : Sub_Arrays;   -- reuse of the somehow generic GNAT.Bubble_Sort (for Ada05)   procedure Sort (Work_Array : in out Sub_Arrays) is procedure Exchange (Op1, Op2 : Natural) is Temp : Integer; begin Temp  := Work_Array (Op1); Work_Array (Op1) := Work_Array (Op2); Work_Array (Op2) := Temp; end Exchange;   function Lt (Op1, Op2 : Natural) return Boolean is begin return (Work_Array (Op1) < Work_Array (Op2)); end Lt; begin GNAT.Bubble_Sort.Sort (N => Subindex_Range'Last, Xchg => Exchange'Unrestricted_Access, Lt => Lt'Unrestricted_Access); end Sort;   begin -- as the positions are not ordered, first sort the positions Sort (Sub_Index); -- extract the values to be sorted for I in Subindex_Range loop Sub_Array (I) := Input_Array (Sub_Index (I)); end loop; Sort (Sub_Array); -- put the sorted values at the right place for I in Subindex_Range loop Input_Array (Sub_Index (I))  := Sub_Array (I); end loop;   for I in Index_Range loop Int_Io.Put (Input_Array (I), Width => 2); end loop; New_Line;   end DisjointSort;
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#COBOL
COBOL
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Common_Lisp
Common Lisp
cities = [ {"UK", "London"}, {"US", "New York"}, {"US", "Birmingham"}, {"UK", "Birmingham"} ]   IO.inspect Enum.sort(cities) IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)