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/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#AutoHotkey
AutoHotkey
oGrid := [[ "", "X", "X"] ; setup oGrid ,[ "X", "X", "X", "X"] ,[ "", "X", "X"]]   oNeighbor := [], oCell := [], oRoute := [] , oVisited := [] ; initialize objects   for row, oRow in oGrid for col, val in oRow if val ; for each valid cell in oGrid oNeighbor[row, col] := Neighbors(row, col, oGrid) ; list valid no-connection neighbors   Solve: for row, oRow in oGrid for col , val in oRow if val ; for each valid cell in oGrid if (oSolution := SolveNoConnect(row, col, 1)).8 ; solve for this cell break, Solve ; if solution found stop   ; show solution for i , val in oSolution oCell[StrSplit(val, ":").1 , StrSplit(val, ":").2] := i   A := oCell[1, 2] , B := oCell[1, 3] C := oCell[2, 1], D := oCell[2, 2] , E := oCell[2, 3], F := oCell[2, 4] G := oCell[3, 2] , H := oCell[3, 3] sol = (   %A% %B% /|\ /|\ / | X | \ / |/ \| \ %C% - %D% - %E% - %F% \ |\ /| / \ | X | / \|/ \|/ %G% %H% ) MsgBox % sol return ;----------------------------------------------------------------------- SolveNoConnect(row, col, val){ global oRoute.push(row ":" col) ; save route oVisited[row, col] := true ; mark this cell visited   if oRoute[8] ; if solution found return true ; end recursion   for each, nn in StrSplit(oNeighbor[row, col], ",") ; for each no-connection neighbor of cell { rowX := StrSplit(nn, ":").1 , colX := StrSplit(nn, ":").2 ; get coords of this neighbor if !oVisited[rowX, colX] ; if not previously visited { oVisited[rowX, colX] := true ; mark this cell visited val++ ; increment if (SolveNoConnect(rowX, colX, val)) ; recurse return oRoute ; if solution found return route } } oRoute.pop() ; Solution not found, backtrack oRoute oVisited[row, col] := false ; Solution not found, remove mark } ;----------------------------------------------------------------------- Neighbors(row, col, oGrid){ ; return distant neighbors of oGrid[row,col] for r , oRow in oGrid for c, v in oRow if (v="X") && (abs(row-r) > 1 || abs(col-c) > 1) list .= r ":"c "," if (row<>2) && oGrid[row, col] list .= oGrid[row, col+1] ? row ":" col+1 "," : oGrid[row, col-1] ? row ":" col-1 "," : "" return Trim(list, ",") }
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#Java
Java
import java.util.*;   public class Numbrix {   final static String[] board = { "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00"};   final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};   static int[][] grid; static int[] clues; static int totalToFill;   public static void main(String[] args) { int nRows = board.length + 2; int nCols = board[0].split(",").length + 2; int startRow = 0, startCol = 0;   grid = new int[nRows][nCols]; totalToFill = (nRows - 2) * (nCols - 2); List<Integer> lst = new ArrayList<>();   for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1);   if (r >= 1 && r < nRows - 1) {   String[] row = board[r - 1].split(",");   for (int c = 1; c < nCols - 1; c++) { int val = Integer.parseInt(row[c - 1]); if (val > 0) lst.add(val); if (val == 1) { startRow = r; startCol = c; } grid[r][c] = val; } } }   clues = lst.stream().sorted().mapToInt(i -> i).toArray();   if (solve(startRow, startCol, 1, 0)) printResult(); }   static boolean solve(int r, int c, int count, int nextClue) { if (count > totalToFill) return true;   if (grid[r][c] != 0 && grid[r][c] != count) return false;   if (grid[r][c] == 0 && nextClue < clues.length) if (clues[nextClue] == count) return false;   int back = grid[r][c]; if (back == count) nextClue++;   grid[r][c] = count; for (int[] move : moves) if (solve(r + move[1], c + move[0], count + 1, nextClue)) return true;   grid[r][c] = back; return false; }   static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) continue; System.out.printf("%2d ", i); } System.out.println(); } } }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation 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 integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Bracmat
Bracmat
{?} (9.)+(-2.)+(1.)+(2.)+(8.)+(0.)+(1.)+(2.) {!} (-2.)+(0.)+2*(1.)+2*(2.)+(8.)+(9.)
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation 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 integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Burlesque
Burlesque
{1 3 2 5 4}><
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Factor
Factor
USING: io qw sequences sorting sorting.human ;   qw{ 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 } [ human<=> ] sort [ print ] each
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "log" "math/big" "sort" "strings" )   var testCases = []string{ "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0", }   // a parsed representation type oid []big.Int   // "constructor" parses string representation func newOid(s string) oid { ns := strings.Split(s, ".") os := make(oid, len(ns)) for i, n := range ns { if _, ok := os[i].SetString(n, 10); !ok || os[i].Sign() < 0 { return nil } } return os }   // "stringer" formats into string representation func (o oid) String() string { s := make([]string, len(o)) for i, n := range o { s[i] = n.String() } return strings.Join(s, ".") }   func main() { // parse test cases os := make([]oid, len(testCases)) for i, s := range testCases { os[i] = newOid(s) if os[i] == nil { log.Fatal("invalid OID") } } // sort sort.Slice(os, func(i, j int) bool { // "less" function must return true if os[i] < os[j] oi := os[i] for x, v := range os[j] { // lexicographic defintion: less if prefix or if element is < if x == len(oi) || oi[x].Cmp(&v) < 0 { return true } if oi[x].Cmp(&v) > 0 { break } } return false }) // output sorted list for _, o := range os { fmt.Println(o) } }
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
#ERRE
ERRE
PROGRAM DISJOINT   DIM LST%[7],INDICES%[2]   DIM L%[7],I%[2],Z%[2] PROCEDURE SHOWLIST(L%[]->O$) LOCAL I% O$="[" FOR I%=0 TO UBOUND(L%,1) DO O$=O$+STR$(L%[I%])+", " END FOR O$=LEFT$(O$,LEN(O$)-2)+"]" END PROCEDURE   PROCEDURE SORT(Z%[]->Z%[]) LOCAL N%,P%,FLIPS% P%=UBOUND(Z%,1) FLIPS%=TRUE WHILE FLIPS% DO FLIPS%=FALSE FOR N%=0 TO P%-1 DO IF Z%[N%]>Z%[N%+1] THEN SWAP(Z%[N%],Z%[N%+1]) FLIPS%=TRUE END FOR END WHILE END PROCEDURE   PROCEDURE SortDisJoint(L%[],I%[]->L%[]) LOCAL J%,N% LOCAL DIM T%[2]   N%=UBOUND(I%,1) FOR J%=0 TO N% DO T%[J%]=L%[I%[J%]] END FOR SORT(I%[]->I%[]) SORT(T%[]->T%[]) FOR J%=0 TO N% DO L%[I%[J%]]=T%[J%] END FOR END PROCEDURE   BEGIN LST%[]=(7,6,5,4,3,2,1,0) INDICES%[]=(6,1,7) SortDisJoint(LST%[],INDICES%[]->LST%[]) ShowList(LST%[]->O$) PRINT(O$) END PROGRAM
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
#Euphoria
Euphoria
include sort.e   function uniq(sequence s) sequence out out = s[1..1] for i = 2 to length(s) do if not find(s[i], out) then out = append(out, s[i]) end if end for return out end function   function disjointSort(sequence s, sequence idx) sequence values idx = uniq(sort(idx)) values = repeat(0, length(idx)) for i = 1 to length(idx) do values[i] = s[idx[i]] end for values = sort(values) for i = 1 to length(idx) do s[idx[i]] = values[i] end for return s end function   constant data = {7, 6, 5, 4, 3, 2, 1, 0} constant indexes = {7, 2, 8}
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).
#PARI.2FGP
PARI/GP
use sort 'stable';
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).
#Pascal
Pascal
use sort 'stable';
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).
#Perl
Perl
use sort 'stable';
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.
#Modula-2
Modula-2
MODULE SortThreeVariables; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE SwapInt(VAR a,b : INTEGER); VAR t : INTEGER; BEGIN t := a; a := b; b := t; END SwapInt;   PROCEDURE Sort3Int(VAR x,y,z : INTEGER); BEGIN IF x<y THEN IF z<x THEN SwapInt(x,z); END; ELSIF y<z THEN SwapInt(x,y); ELSE SwapInt(x,z); END; IF z<y THEN SwapInt(y,z); END; END Sort3Int;   VAR buf : ARRAY[0..63] OF CHAR; a,b,c : INTEGER; BEGIN a := 77444; b := -12; c := 0; FormatString("Before a=[%i]; b=[%i]; c=[%i]\n", buf, a, b, c); WriteString(buf);   Sort3Int(a,b,c); FormatString("Before a=[%i]; b=[%i]; c=[%i]\n", buf, a, b, c); WriteString(buf);   ReadChar; END SortThreeVariables.
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.
#Nanoquery
Nanoquery
import sort   // sorting string literals x = "lion, tigers, and" y = "bears, oh my!" z = "(from the \"Wizard of OZ\")"   varlist = sort({x,y,z})   x = varlist[0] y = varlist[1] z = varlist[2] println x; println y; println z   // sorting integers x = 77444 y = -12 z = 0   varlist = sort({x, y, z})   x = varlist[0] y = varlist[1] z = varlist[2] println x; println y; println 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.
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string write("Sorting Demo for custom comparator") L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] write(" Unsorted Input : ") every write(" ",image(!L)) shellsort(L,cmptask) # most of the RC sorts will work here write(" Sorted Output : ") every write(" ",image(!L)) end   procedure cmptask(a,b) # sort by descending length and ascending lexicographic order for strings of equal length if (*a > *b) | ((*a = *b) & (map(a) << map(b))) then return b 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
#Sather
Sather
class SORT{T < $IS_LT{T}} is   private swap(inout a, inout b:T) is temp ::= a; a := b; b := temp; end;   -- --------------------------------------------------------------------------------- comb_sort(inout a:ARRAY{T}) is gap ::= a.size; swapped ::= true; loop until!(gap <= 1 and ~swapped); if gap > 1 then gap := (gap.flt / 1.25).int; end; i ::= 0; swapped := false; loop until! ( (i + gap) >= a.size ); if (a[i] > a[i+gap]) then swap(inout a[i], inout a[i+gap]); swapped := true; end; i := i + 1; end; end; end; end;   class MAIN is main is a:ARRAY{INT} := |88, 18, 31, 44, 4, 0, 8, 81, 14, 78, 20, 76, 84, 33, 73, 75, 82, 5, 62, 70|; b ::= a.copy; SORT{INT}::comb_sort(inout b); #OUT + b + "\n"; end; 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.
#Python
Python
import random   def bogosort(l): while not in_order(l): random.shuffle(l) return l   def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
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.
#E
E
def bubbleSort(target) { __loop(fn { var changed := false for i in 0..(target.size() - 2) { def [a, b] := target(i, i + 2) if (a > b) { target(i, i + 2) := [b, a] changed := true } } 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.
#MATLAB_.2F_Octave
MATLAB / Octave
function list = gnomeSort(list)   i = 2; j = 3;   while i <= numel(list)   if list(i-1) <= list(i) i = j; j = j+1; else list([i-1 i]) = list([i i-1]); %Swap i = i-1; if i == 1 i = j; j = j+1; end end %if   end %while end %gnomeSort
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.
#REXX
REXX
/*REXX program sorts a list (four groups) of integers using the bead sort algorithm.*/ /* [↓] define two dozen grasshopper numbers. */ gHopper= 1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270 /* [↓] these are also called hexagonal pyramidal #s. */ greenGrocer= 0 4 16 40 80 140 224 336 480 660 880 1144 1456 1820 2240 2720 3264 3876 4560 /* [↓] define twenty-three Bernoulli numerator numbers*/ bernN= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 0' /* [↓] also called the Reduced Totient function, and is*/ /*also called Carmichael lambda, or the LAMBDA function*/ psi= 1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 10 22 2 20 12 18 6 28 4 30 8 10 16 y= gHopper greenGrocer bernN psi /*combine the four lists into one list.*/ call show 'before sort', y /*display the list before sorting. */ say copies('░', 75) /*show long separator line before sort.*/ call show ' after sort', beadSort(y) /*display the list after sorting. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ beadSort: procedure; parse arg low . 1 high . 1 z,$; @.=0 /*$: the list to be sorted. */ do j=1 until z==''; parse var z x z /*pick the meat off the bone.*/ x= x / 1; @.x= @.x + 1 /*normalize X; bump counter.*/ low= min(low, x); high= max(high, x) /*track lowest and highest #.*/ end /*j*/ /* [↓] now, collect the beads*/ do m=low to high; if @.m>0 then $= $ copies(m' ', @.m) end /*m*/ return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg txt,y; z= words(y); w= length(z) do k=1 for z; say right('element',30) right(k,w) txt":" right(word(y,k),9) end /*k*/ return
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
#Julia
Julia
function cocktailsort(a::Vector) b = copy(a) isordered = false lo, hi = 1, length(b) while !isordered && hi > lo isordered = true for i in lo+1:hi if b[i] < b[i-1] b[i-1], b[i] = b[i], b[i-1] isordered = false end end hi -= 1 if isordered || hi ≤ lo break end for i in hi:-1:lo+1 if b[i-1] > b[i] b[i-1], b[i] = b[i], b[i-1] isordered = false end end lo += 1 end return b end   v = rand(-10:10, 10) println("# unordered: $v\n -> ordered: ", cocktailsort(v))
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Bracmat
Bracmat
( ( Holy-Knight = begin colWidth crumbs non-empty pairs path parseLine , display isolateStartCell minDistance numberElementsAndSort , parseBoard reverseList rightAlign solve strlen . "'non-empty' is a pattern that is used several times in bigger patterns." & ( non-empty = =  %@  : ~( "." | "-" | " " | \t | \r | \n ) ) & ( reverseList = a L .  :?L & whl'(!arg:%?a ?arg&!a !L:?L) & !L ) & (strlen=e.@(!arg:? [?e)&!e) & ( rightAlign = string width .  !arg:(?width,?string) & !width+-1*strlen$!string:?width & whl ' ( !width+-1:~<0:?width & " " !string:?string ) & str$!string ) & ( minDistance = board pat1 pat2 minWidth pos1 pos2 pattern .  !arg:(?board,(=?pat1),(=?pat2)) & -1:?minWidth & "Construct a pattern using a template. The pattern finds the smallest distance between any two columns in the input. Assumption: all columns have the same width and columns are separated by one or more spaces. The function can also be used to find the width of the first column by letting pat1 match a new line." & ' ( ? ( $pat1 [?pos1 (? " "|`) ()$pat2 [?pos2  ? &  !pos2+-1*!pos1  : ( <!minWidth | ?&!minWidth:<0 )  : ?minWidth & ~ ) )  : (=?pattern) & "'pattern', by design, always fails. The interesting part is a side effect: the column width." & (@(!board:!pattern)|!minWidth) ) & ( numberElementsAndSort = a sum n . 0:?sum:?n & "An evaluated sum is always sorted. The terms are structured so the sorting order is by row and then by column (both part of 'a')." & whl ' ( !arg:%?a ?arg & 1+!n:?n & (!a,!n)+!sum:?sum ) & "return the sorted list (sum) and also the size of a field that can contain the highest number." & (!sum.strlen$!n+1) ) & ( parseLine = line row columnWidth width col , bins val A M Z cell validPat .  !arg:(?line,?row,?width,?columnWidth,?bins) & 0:?col & "Find the cells and create a pair [row,col] for each. Put each pair in a bin. There are as many bins as there are different values in cells." & '(? ($!non-empty:?val) ?)  : (=?validPat) & whl ' ( @(!line:?cell [!width ?line) & ( @(!cell:!validPat) & (  !bins:?A (!val.?M) ?Z & !A (!val.(!row.!col) !M) !Z | (!val.!row.!col) !bins )  : ?bins | ) & !columnWidth:?width & 1+!col:?col ) & !bins ) & ( parseBoard = board firstColumnWidth columnWidth,row bins line .  !arg:?board & ( minDistance $ (str$(\r \n !arg),(=\n),!non-empty) , minDistance$(!arg,!non-empty,!non-empty) )  : (?firstColumnWidth,?columnWidth) & 0:?row & :?bins & whl ' ( @(!board:?line \n ?board) & parseLine $ (!line,!row,!firstColumnWidth,!columnWidth,!bins)  : ?bins & (!bins:|1+!row:?row) ) & parseLine $ (!board,!row,!firstColumnWidth,!columnWidth,!bins)  : ?bins ) & "Find the first bin with only one pair. Return this pair and the combined pairs in all remaining bins." & ( isolateStartCell = A begin Z valuedPairs pairs .  !arg:?A (?.? [1:?begin) ?Z & !A !Z:?arg & :?pairs & whl ' ( !arg:(?.?valuedPairs) ?arg & !valuedPairs !pairs:?pairs ) & (!begin.!pairs) ) & ( display = board solution row col x y n colWidth .  !arg:(?board,?solution,?colWidth) & out$!board & 0:?row & -1:?col & whl ' ( !solution:((?y.?x),?n)+?solution & whl ' ( !row:<!y & 1+!row:?row & -1:?col & put$\n ) & whl ' ( 1+!col:?col:<!x & put$(rightAlign$(!colWidth,)) ) & put$(rightAlign$(!colWidth,!n)) ) & put$\n ) & ( solve = A Z x y crumbs pairs X Y solution .  !arg:((?y.?x),?crumbs,?pairs) & ( !pairs:&(!y.!x) !crumbs |  !pairs  :  ?A ( (?Y.?X) ?Z & (!x+-1*!X)*(!y+-1*!Y)  : (2|-2) & solve $ ( (!Y.!X) , (!y.!x) !crumbs , !A !Z )  : ?solution ) & !solution ) ) & ( isolateStartCell$(parseBoard$!arg):(?begin.?pairs) | out$"Sorry, I cannot identify a start cell."&~ ) & solve$(!begin,,!pairs):?crumbs & numberElementsAndSort$(reverseList$!crumbs)  : (?path.?colWidth) & display$(!arg,!path,!colWidth) ) & "   0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 " " -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0-----"  : ?boards & whl'(!boards:%?board ?boards&Holy-Knight$!board) & done );
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . Extra credits are available for other interesting designs. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Numbrix puzzle Solve the no connection puzzle
#Elixir
Elixir
# require HLPsolver   adjacent = [{-3, 0}, {0, -3}, {0, 3}, {3, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}]   board = """ . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . """ HLPsolver.solve(board, adjacent)
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . Extra credits are available for other interesting designs. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Numbrix puzzle Solve the no connection puzzle
#Go
Go
package main   import ( "fmt" "sort" )   var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", }   var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, }   var grid [][]int   var totalToFill = 0   func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] })   for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false }   func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return }   func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num }   func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } }   func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#AWK
AWK
  # syntax: GAWK -f SORT_AN_ARRAY_OF_COMPOSITE_STRUCTURES.AWK BEGIN { # AWK lacks structures but one can be simulated using an associative array. arr["eight 8 "] arr["two 2 "] arr["five 5 "] arr["nine 9 "] arr["one 1 "] arr["three 3 "] arr["six 6 "] arr["seven 7 "] arr["four 4 "] arr["ten 10"] arr["zero 0 "] arr["twelve 12"] arr["minus2 -2"] show(1,7,"@val_str_asc","name") # use name part of name-value pair show(8,9,"@val_num_asc","value") # use value part of name-value pair exit(0) } function show(a,b,sequence,description, i,x) { PROCINFO["sorted_in"] = "@unsorted" for (i in arr) { x = substr(i,a,b) sub(/ +/,"",x) arr[i] = x } PROCINFO["sorted_in"] = sequence printf("sorted by %s:",description) for (i in arr) { printf(" %s",arr[i]) } printf("\n") }  
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.)
#Raku
Raku
sub counting-sort (@ints) { my $off = @ints.min; (my @counts)[$_ - $off]++ for @ints; flat @counts.kv.map: { ($^k + $off) xx ($^v // 0) } }   # Testing: constant @age-range = 2 .. 102; my @ages = @age-range.roll(50); say @ages.&counting-sort; say @ages.sort;   say @ages.&counting-sort.join eq @ages.sort.join ?? 'ok' !! 'not ok';
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#C
C
#include <stdbool.h> #include <stdio.h> #include <math.h>   int connections[15][2] = { {0, 2}, {0, 3}, {0, 4}, // A to C,D,E {1, 3}, {1, 4}, {1, 5}, // B to D,E,F {6, 2}, {6, 3}, {6, 4}, // G to C,D,E {7, 3}, {7, 4}, {7, 5}, // H to D,E,F {2, 3}, {3, 4}, {4, 5}, // C-D, D-E, E-F };   int pegs[8]; int num = 0;   bool valid() { int i; for (i = 0; i < 15; i++) { if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) { return false; } } return true; }   void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }   void printSolution() { printf("----- %d -----\n", num++); printf("  %d %d\n", /* */ pegs[0], pegs[1]); printf("%d %d %d %d\n", pegs[2], pegs[3], pegs[4], pegs[5]); printf("  %d %d\n", /* */ pegs[6], pegs[7]); printf("\n"); }   void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { int i; for (i = le; i <= ri; i++) { swap(pegs + le, pegs + i); solution(le + 1, ri); swap(pegs + le, pegs + i); } } }   int main() { int i; for (i = 0; i < 8; i++) { pegs[i] = i + 1; }   solution(0, 8 - 1); return 0; }
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#Julia
Julia
using .Hidato   const numbrixmoves = [[-1, 0], [0, -1], [0, 1], [1, 0]]   board, maxmoves, fixed, starts = hidatoconfigure(numbrix1) printboard(board, " 0 ", " ") hidatosolve(board, maxmoves, numbrixmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)   board, maxmoves, fixed, starts = hidatoconfigure(numbrix2) printboard(board, " 0 ", " ") hidatosolve(board, maxmoves, numbrixmoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)  
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#Kotlin
Kotlin
// version 1.2.0   val example1 = listOf( "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00" )   val example2 = listOf( "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00" )   val moves = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)   lateinit var board: List<String> lateinit var grid: List<IntArray> lateinit var clues: IntArray var totalToFill = 0   fun solve(r: Int, c: Int, count: Int, nextClue: Int): Boolean { if (count > totalToFill) return true val back = grid[r][c] if (back != 0 && back != count) return false if (back == 0 && nextClue < clues.size && clues[nextClue] == count) { return false } var nextClue2 = nextClue if (back == count) nextClue2++ grid[r][c] = count for (m in moves) { if (solve(r + m.second, c + m.first, count + 1, nextClue2)) return true } grid[r][c] = back return false }   fun printResult(n: Int) { println("Solution for example $n:") for (row in grid) { for (i in row) { if (i == -1) continue print("%2d ".format(i)) } println() } }   fun main(args: Array<String>) { for ((n, ex) in listOf(example1, example2).withIndex()) { board = ex val nRows = board.size + 2 val nCols = board[0].split(",").size + 2 var startRow = 0 var startCol = 0 grid = List(nRows) { IntArray(nCols) { -1 } } totalToFill = (nRows - 2) * (nCols - 2) val lst = mutableListOf<Int>() for (r in 0 until nRows) { if (r in 1 until nRows - 1) { val row = board[r - 1].split(",") for (c in 1 until nCols - 1) { val value = row[c - 1].toInt() if (value > 0) lst.add(value) if (value == 1) { startRow = r startCol = c } grid[r][c] = value } } } lst.sort() clues = lst.toIntArray() if (solve(startRow, startCol, 1, 0)) printResult(n + 1) } }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation 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 integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#C
C
#include <stdlib.h> /* qsort() */ #include <stdio.h> /* printf() */   int intcmp(const void *aa, const void *bb) { const int *a = aa, *b = bb; return (*a < *b) ? -1 : (*a > *b); }   int main() { int nums[5] = {2,4,3,1,2}; qsort(nums, 5, sizeof(int), intcmp); printf("result: %d %d %d %d %d\n", nums[0], nums[1], nums[2], nums[3], nums[4]); return 0; }
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Go
Go
package main   import ( "fmt" "log" "math/big" "sort" "strings" )   var testCases = []string{ "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0", }   // a parsed representation type oid []big.Int   // "constructor" parses string representation func newOid(s string) oid { ns := strings.Split(s, ".") os := make(oid, len(ns)) for i, n := range ns { if _, ok := os[i].SetString(n, 10); !ok || os[i].Sign() < 0 { return nil } } return os }   // "stringer" formats into string representation func (o oid) String() string { s := make([]string, len(o)) for i, n := range o { s[i] = n.String() } return strings.Join(s, ".") }   func main() { // parse test cases os := make([]oid, len(testCases)) for i, s := range testCases { os[i] = newOid(s) if os[i] == nil { log.Fatal("invalid OID") } } // sort sort.Slice(os, func(i, j int) bool { // "less" function must return true if os[i] < os[j] oi := os[i] for x, v := range os[j] { // lexicographic defintion: less if prefix or if element is < if x == len(oi) || oi[x].Cmp(&v) < 0 { return true } if oi[x].Cmp(&v) > 0 { break } } return false }) // output sorted list for _, o := range os { fmt.Println(o) } }
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
#F.23
F#
let sortDisjointSubarray data indices = let indices = Set.toArray indices // creates a sorted array let result = Array.copy data Array.map (Array.get data) indices |> Array.sort |> Array.iter2 (Array.set result) indices result     printfn "%A" (sortDisjointSubarray [|7;6;5;4;3;2;1;0|] (set [6;1;7]))
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).
#Phix
Phix
with javascript_semantics sequence test = {{"UK","London"}, {"US","New York"}, {"US","Birmingham"}, {"UK","Birmingham"}} --------------------- -- probably stable -- --------------------- function cmp(object a, object b) return compare(a[2],b[2]) end function pp(custom_sort(cmp,deep_copy(test)),{pp_Nest,1}) ----------------------- -- guaranteed stable -- ----------------------- function tag_cmp(integer i, integer j) integer c = compare(test[i][2],test[j][2]) if c=0 then c = compare(i,j) end if -- (see note) return c end function sequence tags = custom_sort(tag_cmp,shuffle(tagset(4))) pp(extract(test,tags),{pp_Nest,1})
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).
#PHP
PHP
  # First, define a bernoulli sample, of length 26. x <- sample(c(0, 1), 26, replace=T)   x # [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # Give names to the entries. "letters" is a builtin value names(x) <- letters   x # a b c d e f g h i j k l m n o p q r s t u v w x y z # 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # The unstable one, see how "a" appears after "l" now sort(x, method="quick") # z h s u e q x n j r t v w y p o m l a i g f d c b k # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   # The stable sort, letters are ordered in each section sort(x, method="shell") # e h j n q s u x z a b c d f g i k l m o p r t v w y # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  
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.
#Nim
Nim
proc sortThree[T](a, b, c: var T) = # Bubble sort, why not? while not (a <= b and b <= c): if a > b: swap a, b if b > c: swap b, c   proc testWith[T](a, b, c: T) = var (x, y, z) = (a, b, c) echo "Before: ", x, ", ", y, ", ", z sortThree(x, y, z) echo "After: ", x, ", ", y, ", ", z   testWith(6, 4, 2) testWith(0.9, -37.1, 4.0) testWith("lions", "tigers", "bears")
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.
#OCaml
OCaml
let sortrefs list = let sorted = List.map ( ! ) list |> List.sort (fun a b -> if a < b then -1 else if a > b then 1 else 0) in List.iter2 (fun v x -> v := x) list sorted   open Printf   let test () = let x = ref "lions, tigers, and" in let y = ref "bears, oh my!" in let z = ref "(from the \"Wizard of OZ\")" in sortrefs [x; y; z]; print_endline "case 1:"; printf "\tx: %s\n" !x; printf "\ty: %s\n" !y; printf "\tz: %s\n" !z;   let x = ref 77444 in let y = ref (-12) in let z = ref 0 in sortrefs [x; y; z]; print_endline "case 1:"; printf "\tx: %d\n" !x; printf "\ty: %d\n" !y; printf "\tz: %d\n" !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.
#J
J
mycmp=: 1 :'/:u' length_and_lex =: (-@:# ; lower)&> strings=: 'Here';'are';'some';'sample';'strings';'to';'be';'sorted' length_and_lex mycmp strings +-------+------+------+----+----+---+--+--+ |strings|sample|sorted|Here|some|are|be|to| +-------+------+------+----+----+---+--+--+
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.
#Java
Java
import java.util.Comparator; import java.util.Arrays;   public class Test { public static void main(String[] args) { String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};   Arrays.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { int c = s2.length() - s1.length(); if (c == 0) c = s1.compareToIgnoreCase(s2); return c; } });   for (String s: strings) System.out.print(s + " "); } }
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
#Scala
Scala
object CombSort extends App { val ia = Array(28, 44, 46, 24, 19, 2, 17, 11, 25, 4) val ca = Array('X', 'B', 'E', 'A', 'Z', 'M', 'S', 'L', 'Y', 'C')   def sorted[E](input: Array[E])(implicit ord: Ordering[E]): Array[E] = { import ord._ var gap = input.length var swapped = true while (gap > 1 || swapped) { if (gap > 1) gap = (gap / 1.3).toInt swapped = false for (i <- 0 until input.length - gap) if (input(i) >= input(i + gap)) { val t = input(i) input(i) = input(i + gap) input(i + gap) = t swapped = true } } input }   println(s"Unsorted : ${ia.mkString("[", ", ", "]")}") println(s"Sorted  : ${sorted(ia).mkString("[", ", ", "]")}\n")   println(s"Unsorted : ${ca.mkString("[", ", ", "]")}") println(s"Sorted  : ${sorted(ca).mkString("[", ", ", "]")}")   }
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.
#Qi
Qi
  (define remove-element 0 [_ | R] -> R Pos [A | R] -> [A | (remove-element (1- Pos) R)])   (define get-element Pos R -> (nth (1+ Pos) R))   (define shuffle-0 Pos R -> [(get-element Pos R) | (shuffle (remove-element Pos R))])   (define shuffle [] -> [] R -> (shuffle-0 (RANDOM (length R)) R))   (define in-order? [] -> true [A] -> true [A B | R] -> (in-order? [B | R]) where (<= A B) _ -> false)   (define bogosort Suggestion -> Suggestion where (in-order? Suggestion) Suggestion -> (bogosort (shuffle Suggestion)))  
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.
#EchoLisp
EchoLisp
  ;; sorts a vector of objects in place ;; proc is an user defined comparison procedure   (define (bubble-sort V proc) (define length (vector-length V)) (for* ((i (in-range 0 (1- length))) (j (in-range (1+ i) length))) (unless (proc (vector-ref V i) (vector-ref V j)) (vector-swap! V i j))) V)     (define V #( albert antoinette elvis zen simon)) (define (sort/length a b) ;; sort by string length (< (string-length a) (string-length b)))   (bubble-sort V sort/length) → #(zen simon elvis albert antoinette)  
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.
#MAXScript
MAXScript
fn gnomeSort arr = ( local i = 2 local j = 3 while i <= arr.count do ( if arr[i-1] <= arr[i] then ( i = j j += 1 ) else ( swap arr[i-1] arr[i] i -= 1 if i == 1 then ( i = j j += 1 ) ) ) return arr )
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.
#Ruby
Ruby
class Array def beadsort map {|e| [1] * e}.columns.columns.map(&:length) end   def columns y = length x = map(&:length).max Array.new(x) do |row| Array.new(y) { |column| self[column][row] }.compact # Remove nils. end end end   # Demonstration code: p [5,3,1,7,4,1,1].beadsort
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
#Kotlin
Kotlin
// version 1.1.0   fun cocktailSort(a: IntArray) { fun swap(i: Int, j: Int) { val temp = a[i] a[i] = a[j] a[j] = temp } do { var swapped = false for (i in 0 until a.size - 1) if (a[i] > a[i + 1]) { swap(i, i + 1) swapped = true } if (!swapped) break swapped = false for (i in a.size - 2 downTo 0) if (a[i] > a[i + 1]) { swap(i, i + 1) swapped = true } } while (swapped) }   fun main(args: Array<String>) { val aa = arrayOf( intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199), intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1), intArrayOf(62, 83, 18, 53, 7, 17, 95, 86, 47, 69, 25, 28) ) for (a in aa) { cocktailSort(a) println(a.joinToString(", ")) } }
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#C.23
C#
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable;   public class Solver { private static readonly (int dx, int dy)[] //other puzzle types elided knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};   private (int dx, int dy)[] moves;   public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000.."));   Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); }   public Solver(params (int dx, int dy)[] moves) => this.moves = moves;   public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); }   public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); }   private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; }   private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false;   bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); }   private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); }   private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); }   private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; }   private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); }   }
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#ActionScript
ActionScript
import mx.rpc.soap.WebService; import mx.rpc.events.ResultEvent; var ws:WebService = new WebService(); ws.wsdl = 'http://example.com/soap/wsdl'; ws.soapFunc.addEventListener("result",soapFunc_Result); ws.anotherSoapFunc.addEventListener("result",anotherSoapFunc_Result); ws.loadWSDL(); ws.soapFunc(); ws.anotherSoapFunc(); // method invocation callback handlers private function soapFunc_Result(event:ResultEvent):void { // do something } private function anotherSoapFunc_Result(event:ResultEvent):void { // do another something }
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . Extra credits are available for other interesting designs. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Numbrix puzzle Solve the no connection puzzle
#Icon_and_Unicon
Icon and Unicon
global nCells, cMap, best record Pos(r,c)   procedure main(A) puzzle := showPuzzle("Input",readPuzzle()) QMouse(puzzle,findStart(puzzle),&null,0) showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") end   procedure readPuzzle() # Start with a reduced puzzle space p := [[-1],[-1]] nCells := maxCols := 0 every line := !&input do { put(p,[: -1 | -1 | gencells(line) | -1 | -1 :]) maxCols <:= *p[-1] } every put(p, [-1]|[-1]) # Now normalize all rows to the same length every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] return p end   procedure gencells(s) static WS, NWS initial { NWS := ~(WS := " \t") cMap := table() # Map to/from internal model cMap["#"] := -1; cMap["_"] := 0 cMap[-1] := " "; cMap[0] := "_" }   s ? while not pos(0) do { w := (tab(many(WS))|"", tab(many(NWS))) | break w := numeric(\cMap[w]|w) if -1 ~= w then nCells +:= 1 suspend w } end   procedure showPuzzle(label, p) write(label," with ",nCells," cells:") every r := !p do { every c := !r do writes(right((\cMap[c]|c),*nCells+1)) write() } return p end   procedure findStart(p) if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) end   procedure solvePuzzle(puzzle) if path := \best then { repeat { loc := path.getLoc() puzzle[loc.r][loc.c] := path.getVal() path := \path.getParent() | break } return puzzle } end   class QMouse(puzzle, loc, parent, val)   method getVal(); return val; end method getLoc(); return loc; end method getParent(); return parent; end method atEnd(); return nCells = val; end   method visit(r,c) if /best & validPos(r,c) then return Pos(r,c) end   method validPos(r,c) v := val+1 xv := (0 <= puzzle[r][c]) | fail if xv = (v|0) then { # make sure this path hasn't already gone there ancestor := self while xl := (ancestor := \ancestor.getParent()).getLoc() do if (xl.r = r) & (xl.c = c) then fail return } end   initially val := val+1 if atEnd() then return best := self QMouse(puzzle, visit(loc.r-3,loc.c), self, val) QMouse(puzzle, visit(loc.r-2,loc.c-2), self, val) QMouse(puzzle, visit(loc.r, loc.c-3), self, val) QMouse(puzzle, visit(loc.r+2,loc.c-2), self, val) QMouse(puzzle, visit(loc.r+3,loc.c), self, val) QMouse(puzzle, visit(loc.r+2,loc.c+2), self, val) QMouse(puzzle, visit(loc.r, loc.c+3), self, val) QMouse(puzzle, visit(loc.r-2,loc.c+2), self, val) end
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#Babel
Babel
babel> baz ([map "foo" 3 "bar" 17] [map "foo" 4 "bar" 18] [map "foo" 5 "bar" 19] [map "foo" 0 "bar" 20]) < babel> bop baz { <- "foo" lumap ! -> "foo" lumap ! lt? } lssort ! < babel> bop {"foo" lumap !} over ! lsnum ! ( 0 3 4 5 )
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTSALIB" sort% = FN_sortSAinit(0,0)   DIM pair{name$, number%} DIM array{(10)} = pair{} FOR i% = 1 TO DIM(array{()}, 1) READ array{(i%)}.name$, array{(i%)}.number% NEXT   DATA "Eight", 8, "Two", 2, "Five", 5, "Nine", 9, "One", 1 DATA "Three", 3, "Six", 6, "Seven", 7, "Four", 4, "Ten", 10   C% = DIM(array{()}, 1) D% = 1 CALL sort%, array{()}, array{(0)}.number%, array{(0)}.name$   FOR i% = 1 TO DIM(array{()}, 1) PRINT array{(i%)}.name$, array{(i%)}.number% NEXT
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.)
#REXX
REXX
/*REXX pgm sorts an array of integers (can be negative) using the count─sort algorithm.*/ $= '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' #= words($); w= length(#);  !.= 0 /* [↑] a list of some Recaman numbers.*/ m= 1; LO= word($, #); HI= LO /*M: max width of any integer in $ list*/ do j=1 for #; z= word($, j)+0; @.j= z; m= max(m, length(z) ) /*get from $ list*/  !.z= !.z + 1; LO= min(LO, z); HI= max(HI, z) /*find LO and HI.*/ end /*j*/ /*W: max index width for the @. array.*/ call show 'before sort: '; say copies('▓', 55) /*show the before array elements. */ call countSort # /*sort a number of entries of @. array.*/ call show ' after sort: ' /*show the after array elements. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ countSort: parse arg N; x= 1; do k=LO to HI; do x=x for !.k; @.x= k; end /*x*/ end /*k*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: do s=1 for #; say right("element",20) right(s,w) arg(1) right(@.s,m); end; return
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#C.2B.2B
C++
#include <array> #include <iostream> #include <vector>   std::vector<std::pair<int, int>> connections = { {0, 2}, {0, 3}, {0, 4}, // A to C,D,E {1, 3}, {1, 4}, {1, 5}, // B to D,E,F {6, 2}, {6, 3}, {6, 4}, // G to C,D,E {7, 3}, {7, 4}, {7, 5}, // H to D,E,F {2, 3}, {3, 4}, {4, 5}, // C-D, D-E, E-F }; std::array<int, 8> pegs; int num = 0;   void printSolution() { std::cout << "----- " << num++ << " -----\n"; std::cout << " " /* */ << pegs[0] << ' ' << pegs[1] << '\n'; std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n'; std::cout << " " /* */ << pegs[6] << ' ' << pegs[7] << '\n'; std::cout << '\n'; }   bool valid() { for (size_t i = 0; i < connections.size(); i++) { if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) { return false; } } return true; }   void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { for (size_t i = le; i <= ri; i++) { std::swap(pegs[le], pegs[i]); solution(le + 1, ri); std::swap(pegs[le], pegs[i]); } } }   int main() { pegs = { 1, 2, 3, 4, 5, 6, 7, 8 }; solution(0, pegs.size() - 1); return 0; }
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[NeighbourQ, CellDistance, VisualizeHidato, HiddenSingle, \ NakedN, HiddenN, ChainSearch, HidatoSolve, Cornering, ValidPuzzle, \ GapSearch, ReachDelete, GrowNeighbours] NeighbourQ[cell1_, cell2_] := (CellDistance[cell1, cell2] === 1) ValidPuzzle[cells_List, cands_List] := MemberQ[cands, {1}] \[And] MemberQ[cands, {Length[cells]}] \[And] Length[cells] == Length[candidates] \[And] MinMax[Flatten[cands]] === {1, Length[cells]} \[And] (Union @@ cands === Range[Length[cells]]) CellDistance[cell1_, cell2_] := ManhattanDistance[cell1, cell2] VisualizeHidato[cells_List, cands_List, path_ : {}] := Module[{grid, nums, cb, hx, pt}, grid = {EdgeForm[Thick], MapThread[ If[Length[#2] > 1, {FaceForm[], Rectangle[#1]}, {FaceForm[LightGray], Rectangle[#1]}] &, {cells, cands}]}; nums = MapThread[ If[Length[#1] == 1, Text[Style[First[#1], 16], #2 + 0.5 {1, 1}], Text[ Tooltip[Style[Length[#1], Red, 10], #1], #2 + 0.5 {1, 1}]] &, {cands, cells}]; cb = CoordinateBounds[cells]; If[Length[path] > 0, pt = Arrow[# + {0.5, 0.5} & /@ cells[[path]]]; , pt = {}; ]; Graphics[{grid, nums, pt}, PlotRange -> cb + {{-0.5, 1.5}, {-0.5, 1.5}}, ImageSize -> 60 (1 + cb[[1, 2]] - cb[[1, 1]])] ] HiddenSingle[cands_List] := Module[{singles, newcands = cands}, singles = Cases[Tally[Flatten[cands]], {_, 1}]; If[Length[singles] > 0, singles = Sort[singles[[All, 1]]]; newcands = If[ContainsAny[#, singles], Intersection[#, singles], #] & /@ newcands; newcands , cands ] ] HiddenN[cands_List, n_Integer?(# > 1 &)] := Module[{tmp, out}, tmp = cands; tmp = Join @@ MapIndexed[{#1, First[#2]} &, tmp, {2}]; tmp = Transpose /@ GatherBy[tmp, First]; tmp[[All, 1]] = tmp[[All, 1, 1]]; tmp = Select[tmp, 2 <= Length[Last[#]] <= n &]; If[Length[tmp] > 0, tmp = Transpose /@ Subsets[tmp, {n}]; tmp[[All, 2]] = Union @@@ tmp[[All, 2]]; tmp = Select[tmp, Length[Last[#]] == n &]; If[Length[tmp] > 0, (* for each tmp {cands, cells} in each of the cells delete everything except the cands *)   out = cands; Do[ Do[ out[[c]] = Select[out[[c]], MemberQ[t[[1]], #] &]; , {c, t[[2]]} ] , {t, tmp} ]; out , cands ] , cands ] ] NakedN[cands_List, n_Integer?(# > 1 &)] := Module[{tmp, newcands, ids}, tmp = {Range[Length[cands]], cands}\[Transpose]; tmp = Select[tmp, 2 <= Length[Last[#]] <= n &]; If[Length[tmp] > 0, tmp = Transpose /@ Subsets[tmp, {n}]; tmp[[All, 2]] = Union @@@ tmp[[All, 2]]; tmp = Select[tmp, Length[Last[#]] == n &]; If[Length[tmp] > 0, newcands = cands; Do[ ids = Complement[Range[Length[newcands]], t[[1]]]; newcands[[ids]] = DeleteCases[newcands[[ids]], Alternatives @@ t[[2]], \[Infinity]]; , {t, tmp} ]; newcands , cands ] , cands ] ] Cornering[cells_List, cands_List] := Module[{newcands, neighbours, filled, neighboursfiltered, cellid, filledneighours, begin, end, beginend}, filled = Flatten[MapIndexed[If[Length[#1] == 1, #2, {}] &, cands]]; begin = If[MemberQ[cands, {1}], {}, {1}]; end = If[MemberQ[cands, {Length[cells]}], {}, {Length[cells]}]; beginend = Join[begin, end]; neighbours = Outer[NeighbourQ, cells, cells, 1]; neighbours = Association[ MapIndexed[ First[#2] -> {Complement[Flatten[Position[#1, True]], filled], Intersection[Flatten[Position[#1, True]], filled]} &, neighbours]]; KeyDropFrom[neighbours, filled]; neighbours = Select[neighbours, Length[First[#]] == 1 &]; If[Length[neighbours] > 0, newcands = cands; neighbours = KeyValueMap[List, neighbours]; Do[ cellid = n[[1]]; filledneighours = n[[2, 2]]; filledneighours = Join @@ cands[[filledneighours]]; filledneighours = Union[filledneighours - 1, filledneighours + 1]; filledneighours = Union[filledneighours, beginend]; newcands[[cellid]] = Intersection[newcands[[cellid]], filledneighours]; , {n, neighbours} ]; newcands , cands ] ] ChainSearch[cells_, cands_] := Module[{neighbours, sols, out}, neighbours = Outer[NeighbourQ, cells, cells, 1]; neighbours = Association[ MapIndexed[First[#2] -> Flatten[Position[#1, True]] &, neighbours]]; sols = Reap[ChainSearch[neighbours, cands, {}];][[2]]; If[Length[sols] > 0, sols = sols[[1]]; If[Length[sols] > 1, Print["multiple solutions found, showing first"]; ]; sols = First[sols]; out = cands; out[[sols]] = List /@ Range[Length[out]]; out , cands ] ] ChainSearch[neighbours_, cands_List, solcellids_List] := Module[{largest, largestid, next, poss}, largest = Length[solcellids]; largestid = Last[solcellids, 0]; If[largest < Length[cands], next = largest + 1; poss = Flatten[MapIndexed[If[MemberQ[#1, next], First[#2], {}] &, cands]]; If[Length[poss] > 0, If[largest > 0, poss = Intersection[poss, neighbours[largestid]]; ]; poss = Complement[poss, solcellids]; (* can't be in previous path*)   If[Length[poss] > 0, (* there are 'next' ones iterate over, calling this function *) Do[ ChainSearch[neighbours, cands, Append[solcellids, p]] , {p, poss} ] ] , Print["There should be a next!"]; Abort[]; ] , Sow[solcellids] (* we found a solution with this ordering of cells *) ] ] GrowNeighbours[neighbours_, set_List] := Module[{lastdone, ids, newneighbours, old}, old = Join @@ set[[All, All, 1]]; lastdone = Last[set]; ids = lastdone[[All, 1]]; newneighbours = Union @@ (neighbours /@ ids); newneighbours = Complement[newneighbours, old]; (*only new ones*)   If[Length[newneighbours] > 0, Append[set, Thread[{newneighbours, lastdone[[1, 2]] + 1}]] , set ] ] ReachDelete[cells_List, cands_List, neighbours_, startid_] := Module[{seed, distances, val, newcands}, If[MatchQ[cands[[startid]], {_}], val = cands[[startid, 1]]; seed = {{{startid, 0}}}; distances = Join @@ FixedPoint[GrowNeighbours[neighbours, #] &, seed]; If[Length[distances] > 0, distances = Select[distances, Last[#] > 0 &]; If[Length[distances] > 0, newcands = cands; distances[[All, 2]] = Transpose[ val + Outer[Times, {-1, 1}, distances[[All, 2]] - 1]]; Do[newcands[[\[CurlyPhi][[1]]]] = Complement[newcands[[\[CurlyPhi][[1]]]], Range @@ \[CurlyPhi][[2]]]; , {\[CurlyPhi], distances} ]; newcands , cands ] , cands ] , Print["invalid starting point for neighbour search"]; Abort[]; ] ] GapSearch[cells_List, cands_List] := Module[{givensid, givens, neighbours}, givensid = Flatten[Position[cands, {_}]]; givens = {cells[[givensid]], givensid, Flatten[cands[[givensid]]]}\[Transpose]; If[Length[givens] > 0, givens = SortBy[givens, Last]; givens = Split[givens, Last[#2] == Last[#1] + 1 &]; givens = If[Length[#] <= 2, #, #[[{1, -1}]]] & /@ givens; If[Length[givens] > 0, givens = Join @@ givens; If[Length[givens] > 0, neighbours = Outer[NeighbourQ, cells, cells, 1]; neighbours = Association[ MapIndexed[First[#2] -> Flatten[Position[#1, True]] &, neighbours]]; givens = givens[[All, 2]]; Fold[ReachDelete[cells, #1, neighbours, #2] &, cands, givens] , cands ] , cands ] , cands ] ] HidatoSolve[cells_List, cands_List] := Module[{newcands = cands, old}, Print@VisualizeHidato[cells, newcands]; If[ValidPuzzle[cells, cands] \[Or] 1 == 1, old = -1; newcands = GapSearch[cells, newcands]; While[old =!= newcands, old = newcands; newcands = GapSearch[cells, newcands]; If[old === newcands, newcands = HiddenSingle[newcands]; If[old === newcands, newcands = NakedN[newcands, 2]; newcands = HiddenN[newcands, 2]; If[old === newcands, newcands = NakedN[newcands, 3]; newcands = HiddenN[newcands, 3]; If[old === newcands, newcands = Cornering[cells, newcands]; If[old === newcands, newcands = NakedN[newcands, 4]; newcands = HiddenN[newcands, 4]; If[old === newcands \[And] 2 == 3, newcands = NakedN[newcands, 5]; newcands = HiddenN[newcands, 5]; If[old === newcands, newcands = NakedN[newcands, 6]; newcands = HiddenN[newcands, 6]; If[old === newcands, newcands = NakedN[newcands, 7]; newcands = HiddenN[newcands, 7]; If[old === newcands, newcands = NakedN[newcands, 8]; newcands = HiddenN[newcands, 8]; ] ] ] ] ] ] ] ] ] ]; If[Length[Flatten[newcands]] > Length[newcands], (* if not solved do a depth-first brute force search*)   newcands = ChainSearch[cells, newcands]; ]; Print@VisualizeHidato[cells, newcands]; newcands , Print[ "There seems to be something wrong with your Hidato puzzle. Check \ if the begin and endpoints are given, the cells and candidates have \ the same length, all the numbers are among the \ candidates\[Ellipsis]"] ] ]   puzz = "0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0"; puzz = StringSplit[#, " "] & /@ StringSplit[StringReplace[puzz, " " -> " "], "\n"]; puzz = Map[StringTrim /* ToExpression, puzz, {2}]; puzz //= Transpose; puzz //= Map[Reverse]; pos = Position[puzz, Except[0], {2}, Heads -> False]; clues = Thread[{pos, List /@ Extract[puzz, pos]}]; cells = Tuples[Range[9], 2]; candidates = ConstantArray[Range@Length[cells], Length[cells]]; indices = Flatten[Position[cells, #] & /@ clues[[All, 1]]]; candidates[[indices]] = clues[[All, 2]]; out = HidatoSolve[cells, candidates];   puzz = " 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0"; puzz = StringSplit[#, " "] & /@ StringSplit[StringReplace[puzz, " " -> " "], "\n"]; puzz = Map[StringTrim /* ToExpression, puzz, {2}]; puzz //= Transpose; puzz //= Map[Reverse]; pos = Position[puzz, Except[0], {2}, Heads -> False]; clues = Thread[{pos, List /@ Extract[puzz, pos]}]; cells = Tuples[Range[9], 2]; candidates = ConstantArray[Range@Length[cells], Length[cells]]; indices = Flatten[Position[cells, #] & /@ clues[[All, 1]]]; candidates[[indices]] = clues[[All, 2]]; out = HidatoSolve[cells, candidates];
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#Nim
Nim
import algorithm, sequtils, strformat, strutils   const Moves = [(1, 0), (0, 1), (-1, 0), (0, -1)]   type Numbrix = object grid: seq[seq[int]] clues: seq[int] totalToFill: Natural startRow, startCol : Natural     proc initNumbrix(board: openArray[string]): Numbrix =   let nRows = board.len + 2 let nCols = board[0].split(',').len + 2 result.grid = newSeqWith(nRows, repeat(-1, nCols)) result.totalToFill = (nRows - 2) * (nCols - 2)   var list: seq[int] for r in 0..board.high: let row = board[r].split(',') for c in 0..row.high: let val = parseInt(row[c]) result.grid[r + 1][c + 1] = val if val > 0: list.add val if val == 1: result.startRow = r + 1 result.startCol = c + 1   list.sort() result.clues = list     proc solve(numbrix: var Numbrix; row, col, count: Natural; nextClue: int): bool =   if count > numbrix.totalToFill: return true   let back = numbrix.grid[row][col] if back notin [0, count]: return false if back == 0 and nextClue < numbrix.clues.len and numbrix.clues[nextClue] == count: return false   var nextClue = nextClue if back == count: inc nextClue   numbrix.grid[row][col] = count for move in Moves: if numbrix.solve(row + move[1], col + move[0], count + 1, nextClue): return true numbrix.grid[row][col] = back     proc print(numbrix: Numbrix) = for row in numbrix.grid: for val in row: if val != -1: stdout.write &"{val:2} " echo()     when isMainModule:   const   Example1 = ["00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00"]   Example2 = ["00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00"]   for i, board in [1: Example1, 2: Example2]: var numbrix = initNumbrix(board) if numbrix.solve(numbrix.startRow, numbrix.startCol, 1, 0): echo &"Solution for example {i}:" numbrix.print() else: echo "No solution."
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation 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 integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#C.23
C#
using System; using System.Collections.Generic;   public class Program { static void Main() { int[] unsorted = { 6, 2, 7, 8, 3, 1, 10, 5, 4, 9 }; Array.Sort(unsorted); } }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation 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 integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#C.2B.2B
C++
#include <algorithm>   int main() { int nums[] = {2,4,3,1,2}; std::sort(nums, nums+sizeof(nums)/sizeof(int)); return 0; }
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Haskell
Haskell
import Data.List ( sort , intercalate )   splitString :: Eq a => (a) -> [a] -> [[a]] splitString c [] = [] splitString c s = let ( item , rest ) = break ( == c ) s ( _ , next ) = break ( /= c ) rest in item : splitString c next   convertIntListToString :: [Int] -> String convertIntListToString = intercalate "." . map show   orderOID :: [String] -> [String] orderOID = map convertIntListToString . sort . map ( map read . splitString '.' )   oid :: [String] oid = ["1.3.6.1.4.1.11.2.17.19.3.4.0.10" , "1.3.6.1.4.1.11.2.17.5.2.0.79" , "1.3.6.1.4.1.11.2.17.19.3.4.0.4" , "1.3.6.1.4.1.11150.3.4.0.1" , "1.3.6.1.4.1.11.2.17.19.3.4.0.1" , "1.3.6.1.4.1.11150.3.4.0"]   main :: IO ( ) main = do mapM_ putStrLn $ orderOID oid
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
#Factor
Factor
: disjoint-sort! ( values indices -- values' ) over <enumerated> nths unzip swap [ natural-sort ] bi@ pick [ set-nth ] curry 2each ;
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
#Fortran
Fortran
program Example implicit none   integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /) integer :: indices(3) = (/ 7, 2, 8 /)   ! In order to make the output insensitive to index order ! we need to sort the indices first call Isort(indices)   ! Should work with any sort routine as long as the dummy ! argument array has been declared as an assumed shape array ! Standard insertion sort used in this example call Isort(array(indices))   write(*,*) array   contains   subroutine Isort(a) integer, intent(in out) :: a(:) integer :: temp integer :: i, j   do i = 2, size(a) j = i - 1 temp = a(i) do while (j>=1 .and. a(j)>temp) a(j+1) = a(j) j = j - 1 end do a(j+1) = temp end do   end subroutine Isort end program Example
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).
#PicoLisp
PicoLisp
  # First, define a bernoulli sample, of length 26. x <- sample(c(0, 1), 26, replace=T)   x # [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # Give names to the entries. "letters" is a builtin value names(x) <- letters   x # a b c d e f g h i j k l m n o p q r s t u v w x y z # 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # The unstable one, see how "a" appears after "l" now sort(x, method="quick") # z h s u e q x n j r t v w y p o m l a i g f d c b k # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   # The stable sort, letters are ordered in each section sort(x, method="shell") # e h j n q s u x z a b c d f g i k l m o p r t v w y # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  
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).
#PureBasic
PureBasic
  # First, define a bernoulli sample, of length 26. x <- sample(c(0, 1), 26, replace=T)   x # [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # Give names to the entries. "letters" is a builtin value names(x) <- letters   x # a b c d e f g h i j k l m n o p q r s t u v w x y z # 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # The unstable one, see how "a" appears after "l" now sort(x, method="quick") # z h s u e q x n j r t v w y p o m l a i g f d c b k # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   # The stable sort, letters are ordered in each section sort(x, method="shell") # e h j n q s u x z a b c d f g i k l m o p r t v w y # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  
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).
#Python
Python
  # First, define a bernoulli sample, of length 26. x <- sample(c(0, 1), 26, replace=T)   x # [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # Give names to the entries. "letters" is a builtin value names(x) <- letters   x # a b c d e f g h i j k l m n o p q r s t u v w x y z # 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # The unstable one, see how "a" appears after "l" now sort(x, method="quick") # z h s u e q x n j r t v w y p o m l a i g f d c b k # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   # The stable sort, letters are ordered in each section sort(x, method="shell") # e h j n q s u x z a b c d f g i k l m o p r t v w y # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  
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).
#Quackery
Quackery
  # First, define a bernoulli sample, of length 26. x <- sample(c(0, 1), 26, replace=T)   x # [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # Give names to the entries. "letters" is a builtin value names(x) <- letters   x # a b c d e f g h i j k l m n o p q r s t u v w x y z # 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # The unstable one, see how "a" appears after "l" now sort(x, method="quick") # z h s u e q x n j r t v w y p o m l a i g f d c b k # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   # The stable sort, letters are ordered in each section sort(x, method="shell") # e h j n q s u x z a b c d f g i k l m o p r t v w y # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  
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.
#Pascal
Pascal
program sortThreeVariables(output);   type { this Extended Pascal data type may hold up to 25 `char` values } line = string(25);   { this procedure sorts two lines } procedure sortLines(var X, Y: line); { nested procedure allocates space for Z only if needed } procedure swap; var Z: line; begin Z := X; X := Y; Y := Z end; begin { for lexical sorting write `if GT(X, Y) then` } if X > Y then begin swap end end;   { sorts three line variables’s values } procedure sortThreeLines(var X, Y, Z: line); begin { `var` parameters can be modified at the calling site } sortLines(X, Y); sortLines(X, Z); sortLines(Y, Z) end;   { writes given lines on output preceded by `X = `, `Y = ` and `Z = ` } procedure printThreeLines(protected X, Y, Z: line); begin { `protected` paremeters cannot be overwritten } writeLn('X = ', X); writeLn('Y = ', Y); writeLn('Z = ', Z) end;   { === MAIN ============================================================= } var A, B: line; { for demonstration purposes: alternative method to initialize } C: line value '(from the "Wizard of OZ")'; begin A := 'lions, tigers, and'; B := 'bears, oh my!';   sortThreeLines(A, B, C); printThreeLines(A, B, C) end.
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.
#JavaScript
JavaScript
function lengthSorter(a, b) { var result = b.length - a.length; if (result == 0) result = a.localeCompare(b); return result; }   var test = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; test.sort(lengthSorter); alert( test.join(' ') ); // strings sample sorted Here some are be to
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
#Sidef
Sidef
func comb_sort(arr) { var gap = arr.len; var swaps = true; while (gap > 1 || swaps) { gap.div!(1.25).int! if (gap > 1); swaps = false; for i in ^(arr.len - gap) { if (arr[i] > arr[i+gap]) { arr[i, i+gap] = arr[i+gap, i]; swaps = true; } } } return 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.
#Quackery
Quackery
[ true swap dup [] != if [ behead swap witheach [ tuck > if [ dip not conclude ] ] ] drop ] is inorder ( [ --> b )   [ dup inorder not while shuffle again ] is bogosort ( [ --> [ )
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.
#R
R
bogosort <- function(x) { while(is.unsorted(x)) x <- sample(x) x }   n <- c(1, 10, 9, 7, 3, 0) bogosort(n)
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.
#EDSAC_order_code
EDSAC order code
  [Bubble sort demo for Rosetta Code website] [EDSAC program. Initial Orders 2]   [Sorts a list of double-word integers. List must be loaded at an even address. First item gives number of items to follow. Address of list is placed in location 49. List can then be referred to with code letter L.] T49K P300F [<---------- address of list here]   [Subroutine R2, reads positive integers during input of orders. Items separated by F; list ends with #TZ.] GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z   [Tell R2 where to store integers it reads from tape.] T #L ['T m D' in documentation, but this also works]   [Lists of integers, comment out all except one] [10 integers from digits of pi] 10F314159F265358F979323F846264F338327F950288F419716F939937F510582F097494#TZ   [32 integers from digits of e ] [32F 27182818F28459045F23536028F74713526F62497757F24709369F99595749F66967627F 72407663F03535475F94571382F17852516F64274274F66391932F00305992F18174135F 96629043F57290033F42952605F95630738F13232862F79434907F63233829F88075319F 52510190F11573834F18793070F21540891F49934884F16750924F47614606F68082264#TZ]   [Library subroutine P7, prints positive integer at 0D. 35 locations; load at aneven address.] T 56 K GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@   [The EDSAC code below implements the following Pascal program, where the integers to be sorted are in a 1-based array x. Since the assembler used (EdsacPC by Martin Campbell-Kelly) doesn't allow square brackets inside comments, they are replaced here by curly brackets.] [ swapped := true; j := n; // number of items while (swapped and (j >= 2)) do begin swapped := false; for i := 1 to j - 1 do begin // Using temp in the comparison makes the EDSAC code a bit simpler temp := x{i}; if (x{i + 1} < temp) then begin x{i} := x{i + 1}; x{i + 1} := temp; swapped := true; end; end; dec(j); end; ] [Main routine] T 100 K G K [0] P F P F [double-word temporary store] [2] P F [flag for swapped, >= 0 if true, < 0 if false] [3] P F ['A' order for x{j}; implicitly defines j] [4] P 2 F [to change list index by 1, i.e.change address by 2] [5] A #L ['A' order for number of items] [6] A 2#L ['A' order for x{1}] [7] A 4#L ['A' order for x{2}] [8] I2046 F [add to convert 'A' order to 'T' and dec address by 2] [9] K4096 F [(1) minimum 17-bit value (2) teleprinter null] [10] P D [constant 1, used in printing] [11] # F [figure shift] [12] & F [line feed] [13] @ F [carriage return]   [Enter here with acc = 0] [14] T 2 @ [swapped := true] A L [get count, n in Pascal program above] L 1 F [times 4 by shifting] A 5 @ [make 'A' order for x{n}; initializes j := n]   [Start 'while' loop of Pascal program. Here acc = 'A' order for x{j}] [18] U 3 @ [update j] S 7 @ [subtract 'A' order for x{2}] G 56 @ [if j < 2 then done] T F [acc := 0] A 2 @ [test for swapped, acc >= 0 if so] G 56 @ [if not swapped then done] A 9 @ [change acc from >= 0 to < 0] T 2 @ [swapped := false until swap occurs] A 6 @ ['A' order for x{1}; initializes i := 1]   [Start 'for' loop of Pascal program. Here acc = 'A' order for x{i}] [27] U 36 @ [store order] S 3 @ [subtract 'A' order for x{j}] E 52 @ [out of 'for' loop if i >= j] T F [clear acc] A 36 @ [load 'A' order for x{i}] A 4 @ [inc address by 2] U 38 @ [plant 'A' order for x{i + 1}] A 8 @ ['A' to 'T', and dec address by 2] T 42 @ [plant 'T' order for x{i}] [36] A #L [load x{i}; this order implicitly defines i] T #@ [temp := x{i}] [38] A #L [load x{i + 1}] S #@ [acc := x{i + 1} - temp] E 49 @ [don't swap if x{i + 1} >= temp]   [Here to swap x{i} and x{i + 1}] A #@ [restore acc := x{i + 1} after test] [42] T #L [x{i} := x{i + 1}] A 42 @ [load 'T' order for x{i}] A 4 @ [inc address by 2] T 47 @ [plant 'T' order for x{i + 1}] A #@ [load temp] [47] T #L [to x{i + 1}] T 2 @ [swapped := 0 (true)]   [49] T F [clear acc] A 38 @ [load 'A' order for x{i + 1}] G 27 @ [loop (unconditional) to inc i]   [52] T F A 3 @ [load 'A' order for x{j}] S 4 @ [dec address by 2] G 18 @ [loop (unconditional) to dec j]   [Print the sorted list of integers] [56] O 11 @ [figure shift] T F [clear acc] A 5 @ [load 'A' order for head of list] T 65 @ [plant in code below] S L [load negative number of items] [61] T @ [use first word of temp store for count] A 65 @ [load 'A' order for item] A 4 @ [inc address by 2] T 65 @ [store back] [65] A #L [load next item in list] T D [to 0D for printing] [67] A 67 @ [for subroutine return] G 56 F [print integer, clears acc] O 13 @ [print CR] O 12 @ [print LF] A @ [negative count] A 10 @ [add 1] G 61 @ [loop back till count = 0] [74] O 9 @ [null to flush teleprinter buffer] Z F [stop] E 14 Z [define entry point] P F [acc = 0 on entry]  
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.
#Metafont
Metafont
def gnomesort(suffix v)(expr n) = begingroup save i, j, t; i := 1; j := 2; forever: exitif not (i < n); if v[i-1] <= v[i]: i := j; j := j + 1; else: t := v[i-1]; v[i-1] := v[i]; v[i] := t; i := i - 1; i := if i=0: j; j := j + 1 else: i fi; fi endfor endgroup enddef;
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: beadSort (inout array integer: a) is func local var integer: max is 0; var integer: sum is 0; var array bitset: beads is 0 times {}; var integer: i is 0; var integer: j is 0; begin beads := length(a) times {}; for i range 1 to length(a) do if a[i] > max then max := a[i]; end if; beads[i] := {1 .. a[i]}; end for; for j range 1 to max do sum := 0; for i range 1 to length(a) do sum +:= ord(j in beads[i]); excl(beads[i], j); end for; for i range length(a) - sum + 1 to length(a) do incl(beads[i], j); end for; end for; for i range 1 to length(a) do for j range 1 to max until j not in beads[i] do noop; end for; a[i] := pred(j); end for; end func;   const proc: main is func local var array integer: a is [] (5, 3, 1, 7, 4, 1, 1, 20); var integer: num is 0; begin beadSort(a); for num range a do write(num <& " "); end for; writeln; end func;
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.
#Sidef
Sidef
func beadsort(arr) {   var rows = [] var columns = []   for datum in arr { for column in ^datum { ++(columns[column] := 0) ++(rows[columns[column] - 1] := 0) } }   rows.reverse }   say beadsort([5,3,1,7,4,1,1])
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
#Lua
Lua
function cocktailSort( A ) local swapped repeat swapped = false for i = 1, #A - 1 do if A[ i ] > A[ i+1 ] then A[ i ], A[ i+1 ] = A[ i+1 ] ,A[i] swapped=true end end if swapped == false then break -- repeatd loop; end   for i = #A - 1,1,-1 do if A[ i ] > A[ i+1 ] then A[ i ], A[ i+1 ] = A[ i+1 ] , A[ i ] swapped=true end end   until swapped==false end
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#C.2B.2B
C++
  #include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h>   using namespace std;   struct node { int val; unsigned char neighbors; };   class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; }   void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) );   for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; }   solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; }   private: bool search( int x, int y, int w ) { if( w > max ) return true;   node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y );   for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; }   unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; }   void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); }   void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; }   }   int wid, hei, max, dx[8], dy[8]; node* arr; };   int main( int argc, char* argv[] ) { int wid; string p; //p = "* . . . * * * * * . * . . * * * * . . . . . . . . . . * * . * . . * . * * . . . 1 . . . . . . * * * . . * . * * * * * . . . * *"; wid = 8; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }  
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#AutoHotkey
AutoHotkey
WS_Initialize() WS_Exec("Set client = CreateObject(""MSSOAP.SoapClient"")") WS_Exec("client.MSSoapInit ""http://example.com/soap/wsdl""") callhello = client.soapFunc("hello") callanother = client.anotherSoapFunc(34234)   WS_Eval(result, callhello) WS_Eval(result2, callanother) Msgbox % result . "`n" . result2 WS_Uninitialize() #Include ws4ahk.ahk ; http://www.autohotkey.net/~easycom/ws4ahk_public_api.html
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#C
C
  #include <curl/curl.h> #include <string.h> #include <stdio.h>   size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){ return fwrite(ptr,size,nmeb,stream); }   size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){ return fread(ptr,size,nmeb,stream); }   void callSOAP(char* URL, char * inFile, char * outFile) {   FILE * rfp = fopen(inFile, "r"); if(!rfp) perror("Read File Open:");   FILE * wfp = fopen(outFile, "w+"); if(!wfp) perror("Write File Open:");   struct curl_slist *header = NULL; header = curl_slist_append (header, "Content-Type:text/xml"); header = curl_slist_append (header, "SOAPAction: rsc"); header = curl_slist_append (header, "Transfer-Encoding: chunked"); header = curl_slist_append (header, "Expect:"); CURL *curl;   curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, URL); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data); curl_easy_setopt(curl, CURLOPT_READDATA, rfp); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1); curl_easy_setopt(curl, CURLOPT_VERBOSE,1L); curl_easy_perform(curl);   curl_easy_cleanup(curl); } }   int main(int argC,char* argV[]) { if(argC!=4) printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]); else callSOAP(argV[1],argV[2],argV[3]); return 0; }  
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . Extra credits are available for other interesting designs. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Numbrix puzzle Solve the no connection puzzle
#Java
Java
import java.util.*;   public class Hopido {   final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."};   final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[][] grid; static int totalToFill;   public static void main(String[] args) { int nRows = board.length + 6; int nCols = board[0].length() + 6;   grid = new int[nRows][nCols];   for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); for (int c = 3; c < nCols - 3; c++) if (r >= 3 && r < nRows - 3) { if (board[r - 3].charAt(c - 3) == '0') { grid[r][c] = 0; totalToFill++; } } }   int pos = -1, r, c; do { do { pos++; r = pos / nCols; c = pos % nCols; } while (grid[r][c] == -1);   grid[r][c] = 1; if (solve(r, c, 2)) break; grid[r][c] = 0;   } while (pos < nRows * nCols);   printResult(); }   static boolean solve(int r, int c, int count) { if (count > totalToFill) return true;   List<int[]> nbrs = neighbors(r, c);   if (nbrs.isEmpty() && count != totalToFill) return false;   Collections.sort(nbrs, (a, b) -> a[2] - b[2]);   for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; }   return false; }   static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>();   for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; }   static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; }   static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
http://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
Smallest number k such that k+2^m is composite for all m less than k
Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not an element of this sequence. It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite. Task Find and display, here on this page, the first 5 elements of this sequence. See also OEIS:A033939 - Odd k for which k+2^m is composite for all m < k
#Go
Go
package main   import ( "fmt" big "github.com/ncw/gmp" )   // returns true if k is a sequence member, false otherwise func a(k int64) bool { if k == 1 { return false } bk := big.NewInt(k) for m := uint(1); m < uint(k); m++ { n := big.NewInt(1) n.Lsh(n, m) n.Add(n, bk) if n.ProbablyPrime(15) { return false } } return true }   func main() { count := 0 k := int64(1) for count < 5 { if a(k) { fmt.Printf("%d ", k) count++ } k += 2 } fmt.Println() }
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#Bracmat
Bracmat
( (tab=("C++",1979)+(Ada,1983)+(Ruby,1995)+(Eiffel,1985)) & out$"unsorted array:" & lst$tab & out$("sorted array:" !tab \n) & out$"But tab is still unsorted:" & lst$tab );
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#C
C
  #include <stdio.h> #include <stdlib.h> #include <ctype.h>   typedef struct twoStringsStruct { char * key, *value; } sTwoStrings;   int ord( char v ) { static char *dgts = "012345679"; char *cp; for (cp=dgts; v != *cp; cp++); return (cp-dgts); }   int cmprStrgs(const sTwoStrings *s1,const sTwoStrings *s2) { char *p1 = s1->key; char *p2 = s2->key; char *mrk1, *mrk2; while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++;} if (isdigit(*p1) && isdigit(*p2)) { long v1, v2; if ((*p1 == '0') ||(*p2 == '0')) { while (p1 > s1->key) { p1--; p2--; if (*p1 != '0') break; } if (!isdigit(*p1)) { p1++; p2++; } } mrk1 = p1; mrk2 = p2; v1 = 0; while(isdigit(*p1)) { v1 = 10*v1+ord(*p1); p1++; } v2 = 0; while(isdigit(*p2)) { v2 = 10*v2+ord(*p2); p2++; } if (v1 == v2) return(p2-mrk2)-(p1-mrk1); return v1 - v2; } if (tolower(*p1) != tolower(*p2)) return (tolower(*p1) - tolower(*p2)); for(p1=s1->key, p2=s2->key; (*p1 == *p2) && *p1; p1++, p2++); return (*p1 -*p2); }   int maxstrlen( char *a, char *b) { int la = strlen(a); int lb = strlen(b); return (la>lb)? la : lb; }   int main() { sTwoStrings toBsorted[] = { { "Beta11a", "many" }, { "alpha1", "This" }, { "Betamax", "sorted." }, { "beta3", "order" }, { "beta11a", "strings" }, { "beta001", "is" }, { "beta11", "which" }, { "beta041", "be" }, { "beta05", "in" }, { "beta1", "the" }, { "beta40", "should" }, }; #define ASIZE (sizeof(toBsorted)/sizeof(sTwoStrings)) int k, maxlens[ASIZE]; char format[12]; sTwoStrings *cp;   qsort( (void*)toBsorted, ASIZE, sizeof(sTwoStrings),cmprStrgs);   for (k=0,cp=toBsorted; k < ASIZE; k++,cp++) { maxlens[k] = maxstrlen(cp->key, cp->value); sprintf(format," %%-%ds", maxlens[k]); printf(format, toBsorted[k].value); } printf("\n"); for (k=0; k < ASIZE; k++) { sprintf(format," %%-%ds", maxlens[k]); printf(format, toBsorted[k].key); } printf("\n");   return 0; }
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.)
#Ring
Ring
  aList = [4, 65, 2, 99, 83, 782, 1] see countingSort(aList, 1, 782)   func countingSort f, min, max count = list(max-min+1) for i = min to max count[i] = 0 next   for i = 1 to len(f) count[ f[i] ] = count[ f[i] ] + 1 next   z = 1 for i = min to max while count[i] > 0 f[z] = i z = z + 1 count[i] = count[i] - 1 end next return f  
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.)
#Ruby
Ruby
class Array def counting_sort! replace counting_sort end   def counting_sort min, max = minmax count = Array.new(max - min + 1, 0) each {|number| count[number - min] += 1} (min..max).each_with_object([]) {|i, ary| ary.concat([i] * count[i - min])} end end   ary = [9,7,10,2,9,7,4,3,10,2,7,10,2,1,3,8,7,3,9,5,8,5,1,6,3,7,5,4,6,9,9,6,6,10,2,4,5,2,8,2,2,5,2,9,3,3,5,7,8,4] p ary.counting_sort.join(",") # => "1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,5,5,5,5,5,5,6,6,6,6,7,7,7,7,7,7,8,8,8,8,9,9,9,9,9,9,10,10,10,10"   p ary = Array.new(20){rand(-10..10)} # => [-3, -1, 9, -6, -8, -3, 5, -7, 4, 0, 5, 0, 2, -2, -6, 10, -10, -7, 5, -7] p ary.counting_sort # => [-10, -8, -7, -7, -7, -6, -6, -3, -3, -2, -1, 0, 0, 2, 4, 5, 5, 5, 9, 10]
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#Chapel
Chapel
type hole = int; param A : hole = 1; param B : hole = A+1; param C : hole = B+1; param D : hole = C+1; param E : hole = D+1; param F : hole = E+1; param G : hole = F+1; param H : hole = G+1; param starting : int = 0; const holes : domain(hole) = { A,B,C,D,E,F,G,H }; const graph : [holes] domain(hole) = [ A => { C,D,E }, B => { D,E,F }, C => { A,D,G }, D => { A,B,C,E,G,H }, E => { A,B,D,F,G,H }, F => { B,E,H }, G => { C,D,E }, H => { D,E,F } ];   proc check( configuration : [] int, idx : hole ) : bool { var good = true; for adj in graph[idx] { if adj >= idx then continue; if abs( configuration[idx] - configuration[adj] ) <= 1 { good = false; break; } }   return good; }   proc solve( configuration : [] int, pegs : domain(int), idx : hole = A ) : bool { for value in pegs { configuration[idx] = value; if check( configuration, idx ) { if idx < holes.size { var prePegs = pegs; if solve( configuration, prePegs - value, idx + 1 ){ return true; } } else { return true; } } } configuration[idx] = starting; return false; }   proc printBoard( configuration : [] int ){ return "\n " + configuration[A] + " " + configuration[B]+ "\n" + " /|\\ /|\\ \n"+ " / | X | \\ \n"+ " / |/ \\| \\ \n"+ " " + configuration[C] +" - " + configuration[D] + " - " + configuration[E] + " - " + configuration[F] + " \n"+ " \\ |\\ /| / \n"+ " \\ | X | / \n"+ " \\|/ \\|/ \n"+ " " + configuration[G] + " " + configuration[H]+ "\n";   }       proc main(){ var configuration : [holes] int; for idx in holes do configuration[idx] = starting;   var pegs : domain(int) = {1,2,3,4,5,6,7,8}; solve( configuration, pegs );   writeln( printBoard( configuration ) );   }  
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#D
D
void main() @safe { import std.stdio, std.math, std.algorithm, std.traits, std.string;   enum Peg { A, B, C, D, E, F, G, H } immutable Peg[2][15] connections = [[Peg.A, Peg.C], [Peg.A, Peg.D], [Peg.A, Peg.E], [Peg.B, Peg.D], [Peg.B, Peg.E], [Peg.B, Peg.F], [Peg.C, Peg.D], [Peg.D, Peg.E], [Peg.E, Peg.F], [Peg.G, Peg.C], [Peg.G, Peg.D], [Peg.G, Peg.E], [Peg.H, Peg.D], [Peg.H, Peg.E], [Peg.H, Peg.F]];   immutable board = r" A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H";   Peg[EnumMembers!Peg.length] perm = [EnumMembers!Peg]; do if (connections[].all!(con => abs(perm[con[0]] - perm[con[1]]) > 1)) return board.tr("ABCDEFGH", "%(%d%)".format(perm)).writeln; while (perm[].nextPermutation); }
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. Related tasks A* search algorithm Solve a Holy Knight's tour Knight's tour N-queens problem Solve a Hidato puzzle Solve a Holy Knight's tour Solve a Hopido puzzle Solve the no connection puzzle
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings;   $_ = <<END; 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 END   my $gap = /.\n/ * $-[0]; print; s/ (?=\d\b)/0/g; my $max = sprintf "%02d", tr/0-9// / 2;   solve( '01', $_ );   sub solve { my ($have, $in) = @_; $have eq $max and exit !print "solution\n", $in =~ s/\b0/ /gr; if( $in =~ ++(my $want = $have) ) { $in =~ /($have|$want)( |.{$gap})($have|$want)/s and solve($want, $in); } else { ($_ = $in) =~ s/$have \K00/$want/ and solve( $want, $_ ); # R ($_ = $in) =~ s/$have.{$gap}\K00/$want/s and solve( $want, $_ ); # D ($_ = $in) =~ s/00(?= $have)/$want/ and solve( $want, $_ ); # L ($_ = $in) =~ s/00(?=.{$gap}$have)/$want/s and solve( $want, $_ ); # U } }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation 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 integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Clean
Clean
import StdEnv   sortArray :: (a e) -> a e | Array a e & Ord e sortArray array = {y \\ y <- sort [x \\ x <-: array]}   Start :: {#Int} Start = sortArray {2, 4, 3, 1, 2}
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation 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 integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Clojure
Clojure
(sort [5 4 3 2 1]) ; sort can also take a comparator function (1 2 3 4 5)
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#J
J
oids=:<@-.&' ';._2]0 :0 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 )
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Java
Java
  package com.rosettacode;   import java.util.Comparator; import java.util.stream.Stream;   public class OIDListSorting {   public static void main(String[] args) {   final String dot = "\\.";   final Comparator<String> oids_comparator = (o1, o2) -> { final String[] o1Numbers = o1.split(dot), o2Numbers = o2.split(dot); for (int i = 0; ; i++) { if (i == o1Numbers.length && i == o2Numbers.length) return 0; if (i == o1Numbers.length) return -1; if (i == o2Numbers.length) return 1; final int nextO1Number = Integer.valueOf(o1Numbers[i]), nextO2Number = Integer.valueOf(o2Numbers[i]); final int result = Integer.compare(nextO1Number, nextO2Number); if (result != 0) return result; } };   Stream.of("1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0") .sorted(oids_comparator) .forEach(System.out::println); } }
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
#FreeBASIC
FreeBASIC
dim as integer value(0 to 7) = {7, 6, 5, 4, 3, 2, 1, 0} dim as integer index(0 to 2) = {6, 1, 7}, i   for i = 0 to 1 if value(index(i))>value(index(i+1)) then swap value(index(i)), value(index(i+1)) end if next i   for i = 0 to 7 print value(i); next i : print
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).
#R
R
  # First, define a bernoulli sample, of length 26. x <- sample(c(0, 1), 26, replace=T)   x # [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # Give names to the entries. "letters" is a builtin value names(x) <- letters   x # a b c d e f g h i j k l m n o p q r s t u v w x y z # 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # The unstable one, see how "a" appears after "l" now sort(x, method="quick") # z h s u e q x n j r t v w y p o m l a i g f d c b k # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   # The stable sort, letters are ordered in each section sort(x, method="shell") # e h j n q s u x z a b c d f g i k l m o p r t v w y # 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  
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).
#Racket
Racket
  #lang racket   (sort '(("UK" "London") ("US" "New York") ("US" "Birmingham") ("UK" "Birmingham")) string<? #:key first) ;; -> (("UK" "London") ("UK" "Birmingham") ;; ("US" "New York") ("US" "Birmingham"))   (sort '(("UK" "London") ("US" "New York") ("US" "Birmingham") ("UK" "Birmingham")) string<? #:key second) ;; -> '(("US" "Birmingham") ("UK" "Birmingham") ;; ("UK" "London") ("US" "New York"))  
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).
#Raku
Raku
use v6; my @cities = ['UK', 'London'], ['US', 'New York'], ['US', 'Birmingham'], ['UK', 'Birmingham'], ;   .say for @cities.sort: { .[1] };
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).
#REBOL
REBOL
; REBOL's sort function is not stable by default. You need to use a custom comparator to make it so.   blk: [ [UK London] [US New-York] [US Birmingham] [UK Birmingham] ] sort/compare blk func [a b] [either a/2 < b/2 [-1] [either a/2 > b/2 [1] [0]]]   ; Note that you can also do a stable sort without nested blocks. blk: [ UK London US New-York US Birmingham UK Birmingham ] sort/skip/compare blk 2 func [a b] [either a < b [-1] [either a > b [1] [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.
#Perl
Perl
#!/usr/bin/env perl use 5.010_000;   # Sort strings   my $x = 'lions, tigers, and'; my $y = 'bears, oh my!'; my $z = '(from the "Wizard of OZ")';   # When assigning a list to list, the values are mapped ( $x, $y, $z ) = sort ( $x, $y, $z );   say 'Case 1:'; say " x = $x"; say " y = $y"; say " z = $z";   # Sort numbers   $x = 77444; $y = -12; $z = 0;   # The sort function can take a customizing block parameter. # The spaceship operator creates a by-value numeric sort ( $x, $y, $z ) = sort { $a <=> $b } ( $x, $y, $z );   say 'Case 2:'; say " x = $x"; say " y = $y"; say " z = $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.
#jq
jq
def quicksort(cmp): if length < 2 then . # it is already sorted else .[0] as $pivot | reduce .[] as $x # state: [less, equal, greater] ( [ [], [], [] ]; # three empty arrays: if $x == $pivot then .[1] += [$x] # add x to equal else ([$x,$pivot]|cmp) as $order | if $order == 0 then .[1] += [$x] # ditto elif ($order|type) == "number" then if $order < 0 then .[0] += [$x] # add x to less else .[2] += [$x] # add x to greater end else ([$pivot,$x]|cmp) as $order2 | if $order and $order2 then .[1] += [$x] # add x to equal elif $order then .[0] += [$x] # add x to less else .[2] += [$x] # add x to greater end end end ) | (.[0] | quicksort(cmp) ) + .[1] + (.[2] | quicksort(cmp) ) end ;
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.
#Julia
Julia
wl = filter(!isempty, split("""You will rejoice to hear that no disaster has accompanied the commencement of an enterprise which you have regarded with such evil forebodings.""", r"\W+"))   println("Original list:\n - ", join(wl, "\n - ")) sort!(wl; by=x -> (-length(x), lowercase(x))) println("\nSorted list:\n - ", join(wl, "\n - "))  
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
#Swift
Swift
func combSort(inout list:[Int]) { var swapped = true var gap = list.count   while gap > 1 || swapped { gap = gap * 10 / 13   if gap == 9 || gap == 10 { gap = 11 } else if gap < 1 { gap = 1 }   swapped = false   for var i = 0, j = gap; j < list.count; i++, j++ { if list[i] > list[j] { (list[i], list[j]) = (list[j], list[i]) swapped = true } } } }
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
#Tcl
Tcl
proc combsort {input} { set gap [llength $input] while 1 { set gap [expr {int(floor($gap / 1.3))}] set swaps 0 for {set i 0} {$i+$gap < [llength $input]} {incr i} { set j [expr {$i+$gap}] if {[lindex $input $i] > [lindex $input $j]} { set tmp [lindex $input $i] lset input $i [lindex $input $j] lset input $j $tmp incr swaps } } if {$gap <= 1 && !$swaps} break } return $input }   set data {23 76 99 58 97 57 35 89 51 38 95 92 24 46 31 24 14 12 57 78} puts [combsort $data]
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.
#Racket
Racket
  #lang racket (define (bogo-sort l) (if (apply <= l) l (bogo-sort (shuffle l))))   (require rackunit) (check-equal? (bogo-sort '(6 5 4 3 2 1)) '(1 2 3 4 5 6)) (check-equal? (bogo-sort (shuffle '(1 1 1 2 2 2))) '(1 1 1 2 2 2))   (let ((unsorted (for/list ((i 10)) (random 1000)))) (displayln unsorted) (displayln (bogo-sort unsorted)))  
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.
#Raku
Raku
sub bogosort (@list is copy) { @list .= pick(*) until [<=] @list; return @list; }   my @nums = (^5).map: { rand }; say @nums.sort.Str eq @nums.&bogosort.Str ?? 'ok' !! 'not ok';  
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.
#Eiffel
Eiffel
class APPLICATION create make   feature make -- Create and print sorted set do create my_set.make my_set.put_front (2) my_set.put_front (6) my_set.put_front (1) my_set.put_front (5) my_set.put_front (3) my_set.put_front (9) my_set.put_front (8) my_set.put_front (4) my_set.put_front (10) my_set.put_front (7) print ("Before: ") across my_set as ic loop print (ic.item.out + " ") end print ("%NAfter : ") my_set.sort across my_set as ic loop print (ic.item.out + " ") end end   my_set: MY_SORTED_SET [INTEGER] -- Set to be sorted end