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/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.
#Action.21
Action!
DEFINE PTR="CARD" DEFINE PAIR_SIZE="4" DEFINE PAIR_COUNT="1"   TYPE Pair=[PTR name,value]   BYTE ARRAY pairs(100) BYTE count=[0]   PTR FUNC GetItemAddr(INT index) PTR addr   addr=pairs+index*PAIR_SIZE RETURN (addr)   PROC PrintArray() INT i Pair POINTER p   Put('[) FOR i=0 TO count-1 DO IF i>0 THEN Put(' ) FI p=GetItemAddr(i) PrintF("(%S,%S)",p.name,p.value) OD Put(']) PutE() RETURN   PROC Append(CHAR ARRAY n,v) Pair POINTER dst   dst=GetItemAddr(count) dst.name=n dst.value=v count==+1 RETURN   PROC InitData() Append("Warsaw","Poland") Append("Prague","Czech Republic") Append("London","United Kingdom") Append("Paris","France") Append("Madrit","Spain") Append("Berlin","Germany") Append("Rome","Italy") Append("Moscow","Russia") Append("Budapest","Hungary") RETURN   PROC Sort() INT i,j,minpos CHAR ARRAY tmp Pair POINTER p1,p2   FOR i=0 TO count-2 DO minpos=i FOR j=i+1 TO count-1 DO p1=GetItemAddr(minpos) p2=GetItemAddr(j) IF SCompare(p1.name,p2.name)>0 THEN minpos=j FI OD   IF minpos#i THEN p1=GetItemAddr(minpos) p2=GetItemAddr(i) tmp=p1.name p1.name=p2.name p2.name=tmp tmp=p1.value p1.value=p2.value p2.value=tmp FI OD RETURN   PROC Main() InitData() PrintE("Array before sort:") PrintArray() PutE()   Sort() PrintE("Array after sort:") PrintArray() RETURN
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.
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO;   with Ada.Containers.Generic_Array_Sort;   procedure Demo_Array_Sort is   function "+" (S : String) return Unbounded_String renames To_Unbounded_String;   type A_Composite is record Name  : Unbounded_String; Value : Unbounded_String; end record;   function "<" (L, R : A_Composite) return Boolean is begin return L.Name < R.Name; end "<";   procedure Put_Line (C : A_Composite) is begin Put_Line (To_String (C.Name) & " " & To_String (C.Value)); end Put_Line;   type An_Array is array (Natural range <>) of A_Composite;   procedure Sort is new Ada.Containers.Generic_Array_Sort (Natural, A_Composite, An_Array);   Data : An_Array := (1 => (Name => +"Joe", Value => +"5531"), 2 => (Name => +"Adam", Value => +"2341"), 3 => (Name => +"Bernie", Value => +"122"), 4 => (Name => +"Walter", Value => +"1234"), 5 => (Name => +"David", Value => +"19"));   begin Sort (Data); for I in Data'Range loop Put_Line (Data (I)); end loop; end Demo_Array_Sort;
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.)
#PowerShell
PowerShell
  function countingSort($array) { $minmax = $array | Measure-Object -Minimum -Maximum $min, $max = $minmax.Minimum, $minmax.Maximum $count = @(0) * ($max - $min + 1) foreach ($number in $array) { $count[$number - $min] = $count[$number - $min] + 1 } $z = 0 foreach ($i in $min..$max) { while (0 -lt $count[$i - $min]) { $array[$z] = $i $z = $z+1 $count[$i - $min] = $count[$i - $min] - 1 } } $array }   $array = foreach ($i in 1..50) {Get-Random -Minimum 0 -Maximum 26} "$array" "$(countingSort $array)"  
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
#C.2B.2B
C++
  #include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset>   using namespace std; typedef bitset<4> hood_t;   struct node { int val; hood_t neighbors; };   class nSolver { public:   void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false);   for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; }   solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } }   private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;   node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; }   for (int d = 0; d < 4; d++) { if (n.neighbors[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 + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; }   hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int 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) retval.set(xx); } return retval; }   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, 1); if (z > 1) search(x, y, z - 1, -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; }   }   vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; };   //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { int wid; string p; //p = ". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . ."; wid = 9; //p = ". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . ."; wid = 9; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9;   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 (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }  
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.
#AWK
AWK
  # syntax: GAWK -f SORT_AN_INTEGER_ARRAY.AWK BEGIN { split("9,10,3,1234,99,1,200,2,0,-2",arr,",") show("@unsorted","unsorted") show("@val_num_asc","sorted ascending") show("@val_num_desc","sorted descending") exit(0) } function show(sequence,description, i) { PROCINFO["sorted_in"] = sequence for (i in arr) { printf("%s ",arr[i]) } printf("\t%s\n",description) }  
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
#C.23
C#
using System; using System.Linq; using System.Collections.Generic;   public class Program { public static void Main() { var oids = new [] { "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" };   var comparer = Comparer<string>.Create((a, b) => { int c = a.Split('.').Select(int.Parse) .Zip(b.Split('.').Select(int.Parse), (i, j) => i.CompareTo(j)).FirstOrDefault(x => x != 0); return c != 0 ? c : a.Length.CompareTo(b.Length); });   Array.Sort(oids, comparer);   Console.WriteLine(string.Join(Environment.NewLine, oids)); } }
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
#D
D
import std.algorithm, std.range, std.array;   void main() { auto data = [7, 6, 5, 4, 3, 2, 1, 0]; auto indices = [6, 1, 7];   data.indexed(indices.sort()).sort();   assert(data == [7, 0, 5, 4, 3, 2, 1, 6]); }
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).
#Lua
Lua
  Module Stable { Inventory queue alfa Stack New { Data "UK", "London","US", "New York","US", "Birmingham", "UK","Birmingham" While not empty { Append alfa, Letter$:=letter$ } } sort alfa k=Each(alfa) Document A$ NL$={ } While k { A$= Eval$(k, k^)+" "+eval$(k)+NL$ } Clipboard A$ ' write to clipboard Report A$ } Call Stable   Output: UK London UK Birmingham US New York US Birmingham    
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).
#M2000_Interpreter
M2000 Interpreter
  Module Stable { Inventory queue alfa Stack New { Data "UK", "London","US", "New York","US", "Birmingham", "UK","Birmingham" While not empty { Append alfa, Letter$:=letter$ } } sort alfa k=Each(alfa) Document A$ NL$={ } While k { A$= Eval$(k, k^)+" "+eval$(k)+NL$ } Clipboard A$ ' write to clipboard Report A$ } Call Stable   Output: UK London UK Birmingham US New York US Birmingham    
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).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
mylist = {{1, 2, 3}, {4, 5, 6}, {5, 4, 3}, {9, 5, 1}}; Sort[mylist, (#1[[2]] < #2[[2]]) &] #[[Ordering[#[[All, 2]]]]] &[mylist]
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Sidef
Sidef
func lex_order (n) { [range(1, n, n.sgn)...].sort_by { Str(_) } }   [13, 21, -22].each {|n| printf("%4s: %s\n", n, lex_order(n)) }
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Swift
Swift
func lex(n: Int) -> [Int] { return stride(from: 1, through: n, by: n.signum()).map({ String($0) }).sorted().compactMap(Int.init) }   print("13: \(lex(n: 13))") print("21: \(lex(n: 21))") print("-22: \(lex(n: -22))")
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Tcl
Tcl
proc iota {num {start 0} {step 1}} { set res {} set end [+ $start [* $step $num]] for {set n $start} {$n != $end} {incr n $step} { lappend res $n } return $res }   puts [lsort [iota 13 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.
#Ksh
Ksh
  #!/bin/ksh   # Sort three variables that may contain any value (numbers and/or literals)   # # Variables: # xl='lions, tigers, and' yl='bears, oh my!' zl='(from the "Wizard of OZ")'   typeset -i xn=77444 typeset -F yn=-12.0 typeset -i zn=0   # # Functions: #   # # Function _intoarray(x, y, z, arr) - put 3 variables into arr[] # function _intoarray { typeset _x ; nameref _x="$1" typeset _y ; nameref _y="$2" typeset _z ; nameref _z="$3" typeset _arr ; nameref _arr="$4"   _arr=( "${_x}" "${_y}" "${_z}" ) }   # # Function _arraysort(arr) - return sorted array (any type of elements) # function _arraysort { typeset _arr ; nameref _arr="$1" typeset _i _j ; integer _i _j   _sorttype _arr case $? in 0) # Literal sort for (( _i=1; _i<${#_arr[*]}; _i++ )); do _val="${_arr[_i]}" (( _j = _i - 1 )) while (( _j>=0 )) && [[ "${_arr[_j]}" > "${_val}" ]]; do _arr[_j+1]="${_arr[_j]}" (( _j-- )) done _arr[_j+1]="${_val}" done ;;   1) # Numeric sort for (( _i=1; _i<${#_arr[*]}; _i++ )); do _val=${_arr[_i]} (( _j = _i - 1 )) while (( _j>=0 && _arr[_j]>_val )); do _arr[_j+1]=${_arr[_j]} (( _j-- )) done _arr[_j+1]=${_val} done ;; esac }   # # Function _sorttype(_arr) - return 0 = Literal sort; 1 = Numeric sort # function _sorttype { typeset _arr ; nameref _arr="$1" typeset _i ; integer _i   for ((_i=0; _i<${#_arr[*]}; _i++)); do [[ ${_arr[_i]} != *(\-)+(\d)*(\.)*(\d) ]] && return 0 done return 1 }   # # Function _outofarray(x, y, z, arr) - Put array elements into x, y, z # function _outofarray { typeset _x ; nameref _x="$1" typeset _y ; nameref _y="$2" typeset _z ; nameref _z="$3" typeset _arr ; nameref _arr="$4"   _x="${_arr[0]}" _y="${_arr[1]}" _z="${_arr[2]}" }   ###### # main # ######   unset x y z printf "Numeric Variables:\n%s\n%s\n%s\n\n" "${xn}" "${yn}" "${zn}" typeset -a arrayn _intoarray xn yn zn arrayn _arraysort arrayn _outofarray x y z arrayn printf "Sorted Variables:\n%s\n%s\n%s\n\n" "${x}" "${y}" "${z}"   unset x y z printf "Literal Variables:\n%s\n%s\n%s\n\n" "${xl}" "${yl}" "${zl}" typeset -a arrayl _intoarray xl yl zl arrayl _arraysort arrayl _outofarray x y z arrayl printf "Sorted Variables:\n%s\n%s\n%s\n\n" "${x}" "${y}" "${z}"
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#Little_Man_Computer
Little Man Computer
  // Little Man Computer // Sort x, y, z, in ascending order // Based on a sorting network: // if x > z then swap( x, z) // if x > y then swap( x, y) // if y > z then swap( y, z) // with the addition that if the 2nd swap is executed // then the 3rd comparison is not needed.   // Read numbers x, y, z, and display in their original order INP STA x OUT INP STA y OUT INP STA z OUT // Sort so that x <= y <= z, and display in new order LDA z SUB x BRP label1 LDA x STA t LDA z STA x LDA t STA z label1 LDA y SUB x BRP label2 LDA x STA t LDA y STA x LDA t STA y BRA sorted // added to the sorting network label2 LDA z SUB y BRP sorted LDA y STA t LDA z STA y LDA t STA z sorted LDA x OUT LDA y OUT LDA z OUT HLT x DAT y DAT z DAT t DAT // 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.
#FunL
FunL
def preceeds( a, b ) = b.length() < a.length() or b.length() == a.length() and a.compareToIgnoreCase( b ) < 0   println( ["here", "are", "Some", "sample", "strings", "to", "be", "sorted"].sortWith(preceeds) )
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "sort" "strings" )   type sortable []string   func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) }   func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)")   sort.Sort(s) fmt.Println(s, "(sorted)") }
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#REXX
REXX
/*REXX program sorts and displays a stemmed array using the comb sort algorithm. */ call gen /*generate the @ array elements. */ call show 'before sort' /*display the before array elements. */ say copies('▒', 60) /*display a separator line (a fence). */ call combSort # /*invoke the comb sort (with # entries)*/ call show ' after sort' /*display the after array elements. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ combSort: procedure expose @.; parse arg N /*N: is the number of @ elements. */ g= N-1 /*G: is the gap between the sort COMBs*/ do until g<=1 & done; done= 1 /*assume sort is done (so far). */ g= g * 0.8  % 1 /*equivalent to: g= trunc( g / 1.25) */ if g==0 then g= 1 /*handle case of the gap is too small. */ do j=1 until $>=N; $= j+g /*$: a temporary index (pointer). */ if @.j>@.$ then do; _= @.j; @.j= @.$; @.$= _; done= 0; end end /*j*/ end /*until*/ /* [↑] swap two elements in the array.*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: @.=; @.1 = '----polygon--- sides'  ; @.12 = "dodecagon 12" @.2 = '============== =======' ; @.13 = "tridecagon 13" @.3 = 'triangle 3'  ; @.14 = "tetradecagon 14" @.4 = 'quadrilateral 4'  ; @.15 = "pentadecagon 15" @.5 = 'pentagon 5'  ; @.16 = "hexadecagon 16" @.6 = 'hexagon 6'  ; @.17 = "heptadecagon 17" @.7 = 'heptagon 7'  ; @.18 = "octadecagon 18" @.8 = 'octagon 8'  ; @.19 = "enneadecagon 19" @.9 = 'nonagon 9'  ; @.20 = "icosagon 20" @.10 = 'decagon 10'  ; @.21 = "hectogon 100" @.11 = 'hendecagon 11'  ; @.22 = "chiliagon 1000" @.23 = "myriagon 10000" do #=1 while @.#\==''; end /*find how many elements in @ */ #= #-1; w= length(#); return /*adjust # because of DO loop.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: do k=1 for #; say right('element',15) right(k,w) arg(1)":" @.k; end; return
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.
#PicoLisp
PicoLisp
(de bogosort (Lst) (loop (map '((L) (rot L (rand 1 (length L)))) Lst ) (T (apply <= Lst) Lst) ) )
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.
#PL.2FI
PL/I
*process source xref; bogosort: Proc Options(main); Dcl SYSPRINT Print; Dcl (HBOUND,RANDOM,TIME) Builtin; Dcl tim Pic'(9)9'; Dcl timms Pic'(3)9' def tim pos(7); tim=time(); x=random(timms); Dcl a(5) Dec Fixed(5,1) Init(-21,333,0,444.4,1); Dcl (x,y,temp) Dec Fixed(5,1); Dcl (n,bogo,j,u,v) Bin Fixed(31); n=hbound(a); Call tell('un-bogoed'); loop: Do bogo=1 By 1; Do j=1 To n-1; jp=j+1; x=a(j); y=a(jp); if y>=x Then Iterate; u=rand(1,n); Do Until v^=u v=rand(1,n); End; Temp=a(u); a(u)=a(v); a(v)=temp; Iterate loop; End; Leave; End;   Put Edit('number of bogo sorts performed =',bogo)(Skip,a,f(4)); call tell(' bogoed'); Return;   tell: Proc(txt); Dcl txt Char(*); Dcl t Bin Fixed(31); Put Edit(txt)(skip,a); Do t=1 to n; Put Edit(a(t))(Skip,f(6,1)); End; End;   rand: Proc(lo,hi) Returns(Bin Fixed(31)); Dcl (lo,hi,res) Bin Fixed(31); Dcl r Bin Float(31); r=random(); res=r*(hi-lo+1)+lo; Return(res); End; End;
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Dart
Dart
List<num> bubbleSort(List<num> list) { var retList = new List<num>.from(list); var tmp; var swapped = false; do { swapped = false; for(var i = 1; i < retList.length; i++) { if(retList[i - 1] > retList[i]) { tmp = retList[i - 1]; retList[i - 1] = retList[i]; retList[i] = tmp; swapped = true; } } } while(swapped); return retList; }
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.
#Kotlin
Kotlin
// version 1.1.0   fun <T: Comparable<T>> gnomeSort(a: Array<T>, ascending: Boolean = true) { var i = 1 var j = 2 while (i < a.size) if (ascending && (a[i - 1] <= a[i]) || !ascending && (a[i - 1] >= a[i])) i = j++ else { val temp = a[i - 1] a[i - 1] = a[i] a[i--] = temp if (i == 0) i = j++ } }   fun main(args: Array<String>) { val array = arrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199) println("Original  : ${array.asList()}") gnomeSort(array) println("Sorted (asc)  : ${array.asList()}") gnomeSort(array, false) println("Sorted (desc) : ${array.asList()}") }
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.
#PowerShell
PowerShell
Function BeadSort ( [Int64[]] $indata ) { if( $indata.length -gt 1 ) { $min = $indata[ 0 ] $max = $indata[ 0 ] for( $i = 1; $i -lt $indata.length; $i++ ) { if( $indata[ $i ] -lt $min ) { $min = $indata[ $i ] } if( $indata[ $i ] -gt $max ) { $max = $indata[ $i ] } } #Find the min & max $poles = New-Object 'UInt64[]' ( $max - $min + 1 ) $indata | ForEach-Object { $min..$_ | ForEach-Object { $poles[ $_ - $min ] += 1 } } #Add Beads to the poles, already moved to the bottom $min..( $max - 1 ) | ForEach-Object { $i = $_ - $min if( $poles[ $i ] -gt $poles[ $i + 1 ] ) { #No special case needed for min, since there will always be at least 1 = min ( $poles[ $i ] )..( $poles[ $i + 1 ] + 1 ) | ForEach-Object { Write-Output ( $i + $min ) } } } #Output the results in pipeline fashion 1..( $poles[ $max - $min ] ) | ForEach-Object { Write-Output $max #No special case needed for max, since there will always be at least 1 = max } } else { Write-Output $indata } }   $l = 100; BeadSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 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
#J
J
bigToLeft=: (([ (>. , <.) {.@]) , }.@])/ smallToLeft=: (([ (<. , >.) {.@]) , }.@])/ cocktailSort=: |. @: (|. @: smallToLeft @: |. @: bigToLeft ^:_)
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
#AutoHotkey
AutoHotkey
SolveHopido(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){ if (R&&C) ; if neighbors (not first iteration) { Grid[R, C] := ">" num ; place num in current neighbor and mark it visited ">" row:=R, col:=C ; move to current neighbor }   num++ ; increment num if (num=max) ; if reached end return map(Grid) ; return solution   if locked[num] ; if current num is a locked value { row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 ; find row of num col := StrSplit((StrSplit(locked[num], ",").1) , ":").2 ; find col of num if SolveHopido(Grid, Locked, Max, row, col, num) ; solve for current location and value return map(Grid) ; if solved, return solution } else { for each, value in StrSplit(Neighbor(row,col), ",") { R := StrSplit(value, ":").1 C := StrSplit(value, ":").2   if (Grid[R,C] = "") ; a hole or out of bounds || InStr(Grid[R, C], ">") ; visited || Locked[num+1] && !(Locked[num+1]~= "\b" R ":" C "\b") ; not neighbor of locked[num+1] || Locked[num-1] && !(Locked[num-1]~= "\b" R ":" C "\b") ; not neighbor of locked[num-1] || Locked[num] ; locked value || Locked[Grid[R, C]] ; locked cell continue   if SolveHopido(Grid, Locked, Max, row, col, num, R, C) ; solve for current location, neighbor and value return map(Grid) ; if solved, return solution } } num-- ; step back for i, line in Grid for j, element in line if InStr(element, ">") && (StrReplace(element, ">") >= num) Grid[i, j] := 0 } ;-------------------------------- ;-------------------------------- ;-------------------------------- Neighbor(row,col){ return Trim( "" . "," row ":" col-3 . "," row ":" col+3 . "," row-3 ":" col . "," row+3 ":" col   . "," row+2 ":" col+2 . "," row+2 ":" col-2 . "," row-2 ":" col+2 . "," row-2 ":" col-2 , ",") } ;-------------------------------- map(Grid){ for i, row in Grid { for j, element in row line .= (A_Index > 1 ? "`t" : "") element map .= (map<>""?"`n":"") line line := "" } return StrReplace(map, ">") }
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.
#ALGOL_68
ALGOL 68
MODE SORTSTRUCT = PERSON; OP < = (PERSON a,b)BOOL: age OF a < age OF b; PR READ "prelude/sort.a68" PR;   MODE PERSON = STRUCT (STRING name, INT age); FORMAT person repr = $"Name: "g", Age: "g(0)l$;   []SORTSTRUCT person = (("joe", 120), ("foo", 31), ("bar", 51)); printf((person repr, shell sort(person), $l$))
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.)
#PureBasic
PureBasic
Procedure Counting_sort(Array data_array(1), min, max) Define i, j Dim c(max - min)   For i = 0 To ArraySize(data_array()) c(data_array(i) - min) + 1 Next   For i = 0 To ArraySize(c()) While c(i) data_array(j) = i + min j + 1 c(i) - 1 Wend Next EndProcedure
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).
#11l
11l
V connections = [(0, 2), (0, 3), (0, 4), (1, 3), (1, 4), (1, 5), (6, 2), (6, 3), (6, 4), (7, 3), (7, 4), (7, 5), (2, 3), (3, 4), (4, 5)]   F ok(conn, perm) R abs(perm[conn[0]] - perm[conn[1]]) != 1   F solve() [[Int]] r V perm = Array(1..8) L I all(:connections.map(conn -> ok(conn, @perm))) r [+]= copy(perm) I !perm.next_permutation() L.break R r   V solutions = solve() print(‘A, B, C, D, E, F, G, H = ’solutions[0].join(‘, ’))
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
#D
D
import std.stdio, std.conv, std.string, std.range, std.array, std.typecons, std.algorithm;   struct { alias BitSet8 = ubyte; // A set of 8 bits. alias Cell = uint; enum : string { unavailableInCell = "#", availableInCell = "." } enum : Cell { unavailableCell = Cell.max, availableCell = 0 }   this(in string inPuzzle) pure @safe { const rawPuzzle = inPuzzle.splitLines.map!(row => row.split).array; assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular.   gridWidth = rawPuzzle[0].length; gridHeight = rawPuzzle.length; immutable nMaxCells = gridWidth * gridHeight; grid = new Cell[nMaxCells]; auto knownMutable = new bool[nMaxCells + 1]; uint nAvailableMutable = nMaxCells; bool[Cell] seenCells; // To avoid duplicate input numbers.   uint i = 0; foreach (const piece; rawPuzzle.join) { if (piece == unavailableInCell) { nAvailableMutable--; grid[i++] = unavailableCell; continue; } else if (piece == availableInCell) { grid[i] = availableCell; } else { immutable cell = piece.to!Cell; assert(cell > 0 && cell <= nMaxCells); assert(cell !in seenCells); seenCells[cell] = true; knownMutable[cell] = true; grid[i] = cell; }   i++; }   known = knownMutable.idup; nAvailable = nAvailableMutable; }   @disable this();     auto solve() pure nothrow @safe @nogc out(result) { if (!result.isNull) { // Can't verify 'result' here because it's const. // assert(!result.get.join.canFind(availableCell.text));   assert(!grid.canFind(availableCell)); auto values = grid.filter!(c => c != unavailableCell); auto interval = iota(reduce!min(values.front, values.dropOne), reduce!max(values.front, values.dropOne) + 1); assert(values.walkLength == interval.length); assert(interval.all!(c => values.count(c) == 1)); // Quadratic. } } body { auto result = grid .map!(c => (c == unavailableCell) ? unavailableInCell : c.text) .chunks(gridWidth); alias OutRange = Nullable!(typeof(result));   const start = findStart; if (start.isNull) return OutRange();   search(start.r, start.c, start.cell + 1, 1); if (start.cell > 1) { immutable direction = -1; search(start.r, start.c, start.cell + direction, direction); }   if (grid.any!(c => c == availableCell)) return OutRange(); else return OutRange(result); }   private:     bool search(in uint r, in uint c, in Cell cell, in int direction) pure nothrow @safe @nogc { if ((cell > nAvailable && direction > 0) || (cell == 0 && direction < 0) || (cell == nAvailable && known[cell])) return true; // One solution found.   immutable neighbors = getNeighbors(r, c);   if (known[cell]) { foreach (immutable i, immutable rc; shifts) { if (neighbors & (1u << i)) { immutable c2 = c + rc[0], r2 = r + rc[1]; if (grid[r2 * gridWidth + c2] == cell) if (search(r2, c2, cell + direction, direction)) return true; } } return false; }   foreach (immutable i, immutable rc; shifts) { if (neighbors & (1u << i)) { immutable c2 = c + rc[0], r2 = r + rc[1], pos = r2 * gridWidth + c2; if (grid[pos] == availableCell) { grid[pos] = cell; // Try. if (search(r2, c2, cell + direction, direction)) return true; grid[pos] = availableCell; // Restore. } } } return false; }     BitSet8 getNeighbors(in uint r, in uint c) const pure nothrow @safe @nogc { typeof(return) usable = 0;   foreach (immutable i, immutable rc; shifts) { immutable c2 = c + rc[0], r2 = r + rc[1]; if (c2 >= gridWidth || r2 >= gridHeight) continue; if (grid[r2 * gridWidth + c2] != unavailableCell) usable |= (1u << i); }   return usable; }     auto findStart() const pure nothrow @safe @nogc { alias Triple = Tuple!(uint,"r", uint,"c", Cell,"cell"); Nullable!Triple result;   auto cell = Cell.max; foreach (immutable r; 0 .. gridHeight) { foreach (immutable c; 0 .. gridWidth) { immutable pos = gridWidth * r + c; if (grid[pos] != availableCell && grid[pos] != unavailableCell && grid[pos] < cell) { cell = grid[pos]; result = Triple(r, c, cell); } } }   return result; }   static immutable int[2][4] shifts = [[0, -1], [0, 1], [-1, 0], [1, 0]]; immutable uint gridWidth, gridHeight; immutable int nAvailable; immutable bool[] known; // Given known cells of the puzzle. Cell[] grid; // Flattened mutable game grid. }     void main() { // enum NumbrixPuzzle to catch malformed puzzles at compile-time. enum puzzle1 = ". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .".NumbrixPuzzle;   enum puzzle2 = ". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .".NumbrixPuzzle;   enum puzzle3 = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45".NumbrixPuzzle;     foreach (puzzle; [puzzle1, puzzle2, puzzle3]) { auto solution = puzzle.solve; // Solved at run-time. if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", 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.
#Axe
Axe
2→{L₁} 4→{L₁+1} 3→{L₁+2} 1→{L₁+3} 2→{L₁+4}   SortD(L₁,5)
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.
#Babel
Babel
babel> nil { zap {1 randlf 100 rem} 20 times collect ! } nest dup lsnum ! --> Create a list of random numbers ( 20 47 69 71 18 10 92 9 56 68 71 92 45 92 12 7 59 55 54 24 ) babel> ls2lf --> Convert list to array for sorting babel> dup {fnord} merge_sort --> The internal sort operator babel> ar2ls lsnum ! --> Display the results ( 7 9 10 12 18 20 24 45 47 54 55 56 59 68 69 71 71 92 92 92 )
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
#C.2B.2B
C++
#include <string> #include <vector> #include <algorithm> #include <boost/tokenizer.hpp> #include <iostream>   std::vector<std::string> splitOnChar ( std::string & s , const char c ) { typedef boost::tokenizer<boost::char_separator<char>> tokenizer ; std::vector<std::string> parts ; boost::char_separator<char> sep( &c ) ; tokenizer tokens( s , sep ) ; for ( auto it = tokens.begin( ) ; it != tokens.end( ) ; it++ ) parts.push_back( *it ) ; return parts ; }   bool myCompare ( const std::string & s1 , const std::string & s2 ) { std::string firstcopy( s1 ) ; std::string secondcopy ( s2 ) ; std::vector<std::string> firstparts( splitOnChar ( firstcopy, '.' ) ) ; std::vector<std::string> secondparts( splitOnChar ( secondcopy, '.' ) ) ; std::vector<int> numbers1( firstparts.size( ) ) ; std::vector<int> numbers2( secondparts.size( ) ) ; std::transform( firstparts.begin( ) , firstparts.end( ) , numbers1.begin( ) , []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ; std::transform( secondparts.begin( ) , secondparts.end( ) , numbers2.begin( ) , []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ; auto it1 = numbers1.begin( ) ; auto it2 = numbers2.begin( ) ; while ( *it1 == *it2 ) { it1++ ; it2++ ; } if ( it1 == numbers1.end( ) || it2 == numbers2.end( ) ) return std::lexicographical_compare( s1.begin( ) , s1.end( ) , s2.begin( ) , s2.end( ) ) ; return *it1 < *it2 ; }   int main( ) { std::vector<std::string> arrayOID { "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" } ; std::sort( arrayOID.begin( ) , arrayOID.end( ) , myCompare ) ; for ( std::string s : arrayOID ) std::cout << s << '\n' ; return 0 ; }
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
#EchoLisp
EchoLisp
  (define (sort-disjoint values indices) (define sorted (list-sort < (for/list [(v values) (i (in-naturals))] #:when (member i indices) v)))   (for/list [(v values) (i (in-naturals))] (if (not (member i indices)) v (begin0 (first sorted) (set! sorted (rest sorted))))))   (define (task) (sort-disjoint '[7 6 5 4 3 2 1 0] {6 1 7}))   (task) → (7 0 5 4 3 2 1 6)  
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).
#MATLAB
MATLAB
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   class RCSortStability   method main(args = String[]) public constant   cityList = [String "UK London", "US New York", "US Birmingham", "UK Birmingham"]   cn = String[cityList.length]   say say "Before sort:" System.arraycopy(cityList, 0, cn, 0, cityList.length) loop city = 0 to cn.length - 1 say cn[city] end city   cCompNm = Comparator CityComparator() Arrays.sort(cn, cCompNm)   say say "After sort on city:" loop city = 0 to cn.length - 1 say cn[city] end city   say say "Before sort:" System.arraycopy(cityList, 0, cn, 0, cityList.length) loop city = 0 to cn.length - 1 say cn[city] end city   cCompCtry = Comparator CountryComparator() Arrays.sort(cn, cCompCtry)   say say "After sort on country:" loop city = 0 to cn.length - 1 say cn[city] end city say   return   class RCSortStability.CityComparator implements Comparator   method compare(lft = Object, rgt = Object) public binary returns int return (String lft).substring(4).compareTo((String rgt).substring(4))   class RCSortStability.CountryComparator implements Comparator   method compare(lft = Object, rgt = Object) public binary returns int return (String lft).substring(0, 2).compareTo((String rgt).substring(0, 2))  
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).
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   class RCSortStability   method main(args = String[]) public constant   cityList = [String "UK London", "US New York", "US Birmingham", "UK Birmingham"]   cn = String[cityList.length]   say say "Before sort:" System.arraycopy(cityList, 0, cn, 0, cityList.length) loop city = 0 to cn.length - 1 say cn[city] end city   cCompNm = Comparator CityComparator() Arrays.sort(cn, cCompNm)   say say "After sort on city:" loop city = 0 to cn.length - 1 say cn[city] end city   say say "Before sort:" System.arraycopy(cityList, 0, cn, 0, cityList.length) loop city = 0 to cn.length - 1 say cn[city] end city   cCompCtry = Comparator CountryComparator() Arrays.sort(cn, cCompCtry)   say say "After sort on country:" loop city = 0 to cn.length - 1 say cn[city] end city say   return   class RCSortStability.CityComparator implements Comparator   method compare(lft = Object, rgt = Object) public binary returns int return (String lft).substring(4).compareTo((String rgt).substring(4))   class RCSortStability.CountryComparator implements Comparator   method compare(lft = Object, rgt = Object) public binary returns int return (String lft).substring(0, 2).compareTo((String rgt).substring(0, 2))  
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#VBA
VBA
Public Function sortlexicographically(N As Integer) Dim arrList As Object Set arrList = CreateObject("System.Collections.ArrayList") For i = 1 To N arrList.Add CStr(i) Next i arrList.Sort Dim item As Variant For Each item In arrList Debug.Print item & ", "; Next End Function   Public Sub main() Call sortlexicographically(13) End Sub
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#Wren
Wren
import "/sort" for Sort   var a = (1..13).map { |i| "%(i)" }.toList Sort.quick(a) System.print(a)
http://rosettacode.org/wiki/Sort_numbers_lexicographically
Sort numbers lexicographically
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order. Show all output here on this page. Example Given   13, return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].
#zkl
zkl
fcn lexN(n){ n.pump(List,'+(1),"toString").sort().apply("toInt") }
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.
#Lua
Lua
function variadicSort (...) local t = {} for _, x in pairs{...} do table.insert(t, x) end table.sort(t) return unpack(t) end   local testCases = { { x = 'lions, tigers, and', y = 'bears, oh my!', z = '(from the "Wizard of OZ")' }, { x = 77444, y = -12, z = 0 } } for i, case in ipairs(testCases) do x, y, z = variadicSort(case.x, case.y, case.z) print("\nCase " .. i) print("\tx = " .. x) print("\ty = " .. y) print("\tz = " .. z) 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.
#Go
Go
package main   import ( "fmt" "sort" "strings" )   type sortable []string   func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) }   func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)")   sort.Sort(s) fmt.Println(s, "(sorted)") }
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Ring
Ring
  aList = [3,5,1,2,7,4,8,3,6,4,1] see combsort(aList)   func combsort t gapd = 1.2473 gap = len(t) swaps = 0 while gap + swaps > 1 k = 0 swaps = 0 if gap > 1 gap = floor(gap / gapd) ok for k = 1 to len(t) - gap if t[k] > t[k + gap] temp = t[k] t[k] = t[k + gap] t[k + gap] = temp swaps = swaps + 1 ok next end return t  
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.
#PowerShell
PowerShell
function shuffle ($a) { $c = $a.Clone() # make copy to avoid clobbering $a 1..($c.Length - 1) | ForEach-Object { $i = Get-Random -Minimum $_ -Maximum $c.Length $c[$_-1],$c[$i] = $c[$i],$c[$_-1] $c[$_-1] # return newly-shuffled value } $c[-1] # last value }   function isSorted( [Array] $data ) { $sorted = $true for( $i = 1; ( $i -lt $data.length ) -and $sorted; $i++ ) { $sorted = $data[ $i - 1 ] -le $data[ $i ] } $sorted }   function BogoSort ( [Array] $indata ) { $data = $indata.Clone() while( -not ( isSorted $data ) ) { $data = shuffle $indata } $data }   $l = 7; BogoSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } )
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.
#Delphi
Delphi
program TestBubbleSort;   {$APPTYPE CONSOLE}   {.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array   type TItem = Integer; // declare ordinal type for array item {$IFDEF DYNARRAY} TArray = array of TItem; // dynamic array {$ELSE} TArray = array[0..15] of TItem; // static array {$ENDIF}   procedure BubbleSort(var A: TArray); var Item: TItem; K, L, J: Integer;   begin L:= Low(A) + 1; repeat K:= High(A); for J:= High(A) downto L do begin if A[J - 1] > A[J] then begin Item:= A[J - 1]; A[J - 1]:= A[J]; A[J]:= Item; K:= J; end; end; L:= K + 1; until L > High(A); end;   var A: TArray; I: Integer;   begin {$IFDEF DYNARRAY} SetLength(A, 16); {$ENDIF} for I:= Low(A) to High(A) do A[I]:= Random(100); for I:= Low(A) to High(A) do Write(A[I]:3); Writeln; BubbleSort(A); for I:= Low(A) to High(A) do Write(A[I]:3); Writeln; Readln; end.
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.
#Lua
Lua
function gnomeSort(a) local i, j = 2, 3   while i <= #a do if a[i-1] <= a[i] then i = j j = j + 1 else a[i-1], a[i] = a[i], a[i-1] -- swap i = i - 1 if i == 1 then -- 1 instead of 0 i = j j = j + 1 end end end end
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#PureBasic
PureBasic
#MAXNUM=100   Dim MyData(Random(15)+5) Global Dim Abacus(0,0)   Declare BeadSort(Array InData(1)) Declare PresentData(Array InData(1))   If OpenConsole() Define i ;- Generate a random array For i=0 To ArraySize(MyData()) MyData(i)=Random(#MAXNUM) Next i PresentData(MyData()) ; ;- Sort the array BeadSort(MyData()) PresentData(MyData()) ; Print("Press ENTER to exit"): Input() EndIf   Procedure LetFallDown(x) Protected y=ArraySize(Abacus(),2)-1 Protected ylim=y While y>=0 If Abacus(x,y) And Not Abacus(x,y+1) Swap Abacus(x,y), Abacus(x,y+1) If y<ylim: y+1: Continue: EndIf Else y-1 EndIf Wend EndProcedure   Procedure BeadSort(Array n(1)) Protected i, j, k NewList T() Dim Abacus(#MAXNUM,ArraySize(N())) ;- Set up the abacus For i=0 To ArraySize(Abacus(),2) For j=1 To N(i) Abacus(j,i)=#True Next Next ;- sort it in threads to simulate free beads falling down For i=0 To #MAXNUM AddElement(T()): T()=CreateThread(@LetFallDown(),i) Next ForEach T() WaitThread(T()) Next ;- send it back to a normal array For j=0 To ArraySize(Abacus(),2) k=0 For i=0 To ArraySize(Abacus()) k+Abacus(i,j) Next N(j)=k Next EndProcedure   Procedure PresentData(Array InData(1)) Protected n, m, sum PrintN(#CRLF$+"The array is;") For n=0 To ArraySize(InData()) m=InData(n): sum+m Print(Str(m)+" ") Next PrintN(#CRLF$+"And its sum= "+Str(sum)) EndProcedure
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
#Java
Java
public static void cocktailSort( int[] A ){ boolean swapped; do { swapped = false; for (int i =0; i<= A.length - 2;i++) { if (A[ i ] > A[ i + 1 ]) { //test whether the two elements are in the wrong order int temp = A[i]; A[i] = A[i+1]; A[i+1]=temp; swapped = true; } } if (!swapped) { //we can exit the outer loop here if no swaps occurred. break; } swapped = false; for (int i= A.length - 2;i>=0;i--) { if (A[ i ] > A[ i + 1 ]) { int temp = A[i]; A[i] = A[i+1]; A[i+1]=temp; swapped = true; } } //if no elements have been swapped, then the list is sorted } while (swapped); }
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
#11l
11l
V moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ]   F solve(&pz, sz, sx, sy, idx, cnt) I idx > cnt R 1   L(i) 0 .< :moves.len V x = sx + :moves[i][0] V y = sy + :moves[i][1] I sz > x & x > -1 & sz > y & y > -1 & pz[x][y] == 0 pz[x][y] = idx I 1 == solve(&pz, sz, x, y, idx + 1, cnt) R 1 pz[x][y] = 0 R 0   F find_solution(pz, sz) V p = [[-1] * sz] * sz V idx = 0 V x = 0 V y = 0 V cnt = 0 L(j) 0 .< sz L(i) 0 .< sz I pz[idx] == ‘x’ p[i][j] = 0 cnt++ E I pz[idx] == ‘s’ p[i][j] = 1 cnt++ x = i y = j idx++   I 1 == solve(&p, sz, x, y, 2, cnt) L(j) 0 .< sz L(i) 0 .< sz I p[i][j] != -1 print(‘ #02’.format(p[i][j]), end' ‘’) E print(‘ ’, end' ‘’) print() E print(‘Cannot solve this puzzle!’)   find_solution(‘.xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..’, 8) print() find_solution(‘.....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....’, 13)
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
#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 hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},   private (int dx, int dy)[] moves;   public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...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/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.
#AppleScript
AppleScript
use framework "Foundation"   ----- SORTING COMPOSITE STRUCTURES (BY MULTIPLE KEYS) ------   -- List of {strKey, blnAscending} pairs -> list of records -> sorted list of records   -- sortByComparing :: [(String, Bool)] -> [Record] -> [Record] on sortByComparing(keyDirections, xs) set ca to current application   script recDict on |λ|(x) ca's NSDictionary's dictionaryWithDictionary:x end |λ| end script set dcts to map(recDict, xs)   script asDescriptor on |λ|(kd) set {k, d} to kd ca's NSSortDescriptor's sortDescriptorWithKey:k ascending:d selector:dcts end |λ| end script   ((ca's NSArray's arrayWithArray:dcts)'s ¬ sortedArrayUsingDescriptors:map(asDescriptor, keyDirections)) as list end sortByComparing     --------------------------- TEST --------------------------- on run set xs to [¬ {city:"Shanghai ", pop:24.2}, ¬ {city:"Karachi ", pop:23.5}, ¬ {city:"Beijing ", pop:21.5}, ¬ {city:"Sao Paulo ", pop:24.2}, ¬ {city:"Dhaka ", pop:17.0}, ¬ {city:"Delhi ", pop:16.8}, ¬ {city:"Lagos ", pop:16.1}]   -- Boolean true for ascending order, false for descending:   sortByComparing([{"pop", false}, {"city", true}], xs) end run     -------------------- GENERIC FUNCTIONS ---------------------   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
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.)
#Python
Python
>>> from collections import defaultdict >>> def countingSort(array, mn, mx): count = defaultdict(int) for i in array: count[i] += 1 result = [] for j in range(mn,mx+1): result += [j]* count[j] return result   >>> data = [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] >>> mini,maxi = 1,10 >>> countingSort(data, mini, maxi) == sorted(data) True
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).
#Ada
Ada
  With Ada.Text_IO, Connection_Types, Connection_Combinations;   procedure main is Result : Connection_Types.Partial_Board renames Connection_Combinations; begin Ada.Text_IO.Put_Line( Connection_Types.Image(Result) ); end;
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).
#APL
APL
      perms←{ ⍝∇ 20100513/20140818 ra⌈ --()-- 1=⍴⍴⍵:⍵[∇ ''⍴⍴⍵] ↑{0∊⍴⍵:⍵ ⋄ (⍺[1]⌷⍵),(1↓⍺)∇ ⍵~⍺[1]⌷⍵}∘(⍳⍵)¨↓⍉1+(⌽⍳⍵)⊤¯1+⍳!⍵ }   solution←{ links← (3 4 5) (4 5 6) (1 4 7) (1 2 3 5 7 8) (1 2 4 6 7 8) (2 5 8) (3 4 5) (4 5 6) ⍝ node i connects with nodes i⊃links tries←8 perms 8 fails←{1∊{1∊⍵∊¯1 0 1}¨|⍺-¨⍺∘{⍺[⍵]}¨⍵} ⍝ ⍴⍸~tries fails ⍤1⊢links ⍝ 16 solns←⍸~tries fails ⍤1⊢links tries[''⍴solns;] }  
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
#Elixir
Elixir
# require HLPsolver   adjacent = [{-1, 0}, {0, -1}, {0, 1}, {1, 0}]   board1 = """ 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 """ HLPsolver.solve(board1, adjacent)   board2 = """ 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 """ HLPsolver.solve(board2, adjacent)
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
#Go
Go
package main   import ( "fmt" "sort" "strconv" "strings" )   var example1 = []string{ "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", }   var example2 = []string{ "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", }   var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}   var ( grid [][]int clues []int totalToFill = 0 )   func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true }   back := grid[r][c]   if back != 0 && back != count { return false }   if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false }   if back == count { nextClue++ }   grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false }   func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } }   func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int   for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } }   sort.Ints(lst) clues = lst 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.
#BaCon
BaCon
' Sort an integer array DECLARE values[5] TYPE NUMBER values[0] = 23 values[1] = 32 values[2] = 12 values[3] = 21 values[4] = 01   SORT values   FOR i = 0 TO 3 PRINT values[i], ", "; NEXT PRINT values[4]
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.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" sort% = FN_sortinit(0,0)   DIM array(8) array() = 8, 2, 5, 9, 1, 3, 6, 7, 4   C% = DIM(array(),1) + 1 CALL sort%, array(0)   FOR i% = 0 TO DIM(array(),1) - 1 PRINT ; array(i%) ", "; NEXT PRINT ; array(i%)
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
#Clojure
Clojure
  (defn oid-vec [oid-str] (->> (clojure.string/split oid-str #"\.") (map #(Long. %))))   (defn oid-str [oid-vec] (clojure.string/join "." oid-vec))   ;; ;; If vals differ before shorter vec ends, ;; use comparison of that "common header". ;; If common part matches, compare based on num elements. ;; (defn oid-compare [a b] (let [min-len (min (count a) (count b)) common-cmp (compare (vec (take min-len a)) (vec (take min-len b)))] (if (zero? common-cmp) (compare (count a) (count b)) common-cmp)))   (defn sort-oids [oid-strs] (->> (map oid-vec oid-strs) (sort oid-compare) (map oid-str)))  
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
#Elena
Elena
import extensions; import system'routines; import system'culture;   extension op { sortSublist(indices) { var subList := indices.orderBy:(x => x) .zipBy(indices.selectBy:(i => self[i]) .orderBy:(x => x), (index,val => new{ Index = index; Value = val; })) .toArray();   var list := self.clone(); subList.forEach:(r) { list[r.Index] := r.Value };   ^ list } }   public program() { var list := new int[]{ 7, 6, 5, 4, 3, 2, 1, 0 };   console.printLine(list.sortSublist(new int[]{6, 1, 7}).asEnumerable()) }
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
#Elixir
Elixir
defmodule Sort_disjoint do def sublist(values, indices) when is_list(values) and is_list(indices) do indices2 = Enum.sort(indices) selected = select(values, indices2, 0, []) |> Enum.sort replace(values, Enum.zip(indices2, selected), 0, []) end   defp select(_, [], _, selected), do: selected defp select([val|t], [i|rest], i, selected), do: select(t, rest, i+1, [val|selected]) defp select([_|t], indices, i, selected), do: select(t, indices, i+1, selected)   defp replace(values, [], _, list), do: Enum.reverse(list, values) defp replace([_|t], [{i,v}|rest], i, list), do: replace(t, rest, i+1, [v|list]) defp replace([val|t], indices, i, list), do: replace(t, indices, i+1, [val|list]) end   values = [7, 6, 5, 4, 3, 2, 1, 0] indices = [6, 1, 7] IO.inspect Sort_disjoint.sublist(values, indices)
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).
#Nim
Nim
import algorithm   const Records = [(country: "UK", city: "London"), (country: "US", city: "New York"), (country: "US", city: "Birmingham"), (country: "UK", city: "Birmingham")]   echo "Original order:" for record in Records: echo record.country, " ", record.city echo()   echo "Sorted by city name:" for record in Records.sortedByIt(it.city): echo record.country, " ", record.city echo()   echo "Sorted by country name:" for record in Records.sortedByIt(it.country): echo record.country, " ", record.city
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).
#OCaml
OCaml
/* Rexx */ Do cities = .array~of('UK London', 'US New York', 'US Birmingham', 'UK Birmingham',)   Say; Say 'Original table' Call display cities   Say; Say 'Unstable sort on city' sorted = cities~copy sorted~sortWith(.ColumnComparator~new(4, 20)) Call display sorted   Say; Say 'Stable sort on city' sorted = cities~copy sorted~stableSortWith(.ColumnComparator~new(4, 20)) Call display sorted   Say; Say 'Unstable sort on country' sorted = cities~copy sorted~sortWith(.ColumnComparator~new(1, 2)) Call display sorted   Say; Say 'Stable sort on country' sorted = cities~copy sorted~stableSortWith(.ColumnComparator~new(1, 2)) Call display sorted   Return End Exit   display: Procedure Do Use arg CT   Say '-'~copies(80) Loop c_ over CT Say c_ End c_   Return End Exit  
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).
#ooRexx
ooRexx
/* Rexx */ Do cities = .array~of('UK London', 'US New York', 'US Birmingham', 'UK Birmingham',)   Say; Say 'Original table' Call display cities   Say; Say 'Unstable sort on city' sorted = cities~copy sorted~sortWith(.ColumnComparator~new(4, 20)) Call display sorted   Say; Say 'Stable sort on city' sorted = cities~copy sorted~stableSortWith(.ColumnComparator~new(4, 20)) Call display sorted   Say; Say 'Unstable sort on country' sorted = cities~copy sorted~sortWith(.ColumnComparator~new(1, 2)) Call display sorted   Say; Say 'Stable sort on country' sorted = cities~copy sorted~stableSortWith(.ColumnComparator~new(1, 2)) Call display sorted   Return End Exit   display: Procedure Do Use arg CT   Say '-'~copies(80) Loop c_ over CT Say c_ End c_   Return End Exit  
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.
#M2000_Interpreter
M2000 Interpreter
  Module Sort3 { Let X=77744, Y=-12, Z=0 Let X$ = "lions, tigers, and", Y$ = "bears, oh my!", Z$ = {(from the "Wizard of OZ")} \\ & use for by reference pass Module SortSome (&X$, &Y$, &Z$){ If Type$(X$)<>"String" Then { Link X$,Y$, Z$ to X,Y,Z Print3() If Y>Z then Swap Y, Z ' both numeric in Swap If X>Z then Swap X, Z If X>Y then Swap X, Y Print3() } Else { Print3Str() If Y$>Z$ then Swap Y$, Z$ ' both strings in Swap If X$>Z$ then Swap X$, Z$ If X$>Y$ then Swap X$, Y$ Print3Str() } } SortSome &X, &Y, &Z SortSome &X$, &Y$, &Z$ Sub Print3() \\ double ,, used to insert a New Line Print "X=",X,,"Y=",Y,,"Z=",Z End Sub Sub Print3Str() Print "X$=",X$,,"Y$=",Y$,,"Z$=",Z$ End Sub } Sort3  
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.
#Maple
Maple
lst := sort([x,y,z]): x,y,z := lst[1],lst[2],lst[3]:
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.
#Groovy
Groovy
def strings = "Here are some sample strings to be sorted".split() strings.sort { x, y -> y.length() <=> x.length() ?: x.compareToIgnoreCase(y) } println strings
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
#Ruby
Ruby
class Array def combsort! gap = size swaps = true while gap > 1 or swaps gap = [1, (gap / 1.25).to_i].max swaps = false 0.upto(size - gap - 1) do |i| if self[i] > self[i+gap] self[i], self[i+gap] = self[i+gap], self[i] swaps = true end end end self end end   p [23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78].combsort!
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.
#Prolog
Prolog
bogo_sort(L,Rl) :- min_list(L,Min), repeat, random_permutation(L,Rl), is_sorted(Rl,Min), !.   is_sorted([],_). is_sorted([N|T],P) :- N >= P, is_sorted(T,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.
#Draco
Draco
/* Bubble sort an array of integers */ proc nonrec bubblesort([*] int a) void: bool sorted; int i, temp; sorted := false; while not sorted do sorted := true; for i from 1 upto dim(a,1)-1 do if a[i-1] > a[i] then sorted := false; temp := a[i-1]; a[i-1] := a[i]; a[i] := temp fi od od corp   /* Test */ proc nonrec main() void: int i; [10] int a = (9, -5, 3, 3, 24, -16, 3, -120, 250, 17);   write("Before sorting: "); for i from 0 upto 9 do write(a[i]:5) od; writeln();   bubblesort(a); write("After sorting: "); for i from 0 upto 9 do write(a[i]:5) od corp
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.
#Maple
Maple
arr := Array([17,3,72,0,36,2,3,8,40,0]): len := numelems(arr): i := 2: while (i <= len) do if (i=1 or arr[i] >= arr[i-1]) then i++: else temp:= arr[i]: arr[i] := arr[i-1]: arr[i-1] := temp: i--: end if: end do: 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.
#Python
Python
  #!/bin/python3 from itertools import zip_longest   # This is wrong, it works only on specific examples def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))     # Demonstration code: print(beadsort([5,3,1,7,4,1,1]))  
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#QB64
QB64
  #lang QB64 '*************************************************** '* BeadSort is VERY fast for small CGSortLibArray(max)-CGSortLibArray(min). Typical performance is '* O(NlogN) or better. However as the key values (array values and ranges) go up, the performance '* drops steeply excellent for small-ranged arrays. Integer only at this point. Throughput is '* roughly 900k/GHzS for double-precision, with binary range (0,1). Related to CountingSort() '*************************************************** SUB BeadSort (CGSortLibArray() AS DOUBLE, start AS LONG, finish AS LONG, order&) DIM MAX AS DOUBLE: MAX = CGSortLibArray(start) DIM BeadSort_Sum AS DOUBLE DIM BeadSort_I AS LONG DIM BeadSort_J AS LONG FOR BeadSort_I = start + 1 TO (finish - start) IF (CGSortLibArray(BeadSort_I) > MAX) THEN MAX = CGSortLibArray(BeadSort_I) NEXT REDIM beads((finish - start), MAX) FOR BeadSort_I = 0 TO (finish - start) - 1 FOR BeadSort_J = 0 TO CGSortLibArray(BeadSort_I) - 1 beads(BeadSort_I, BeadSort_J) = 1 NEXT NEXT IF order& = 1 THEN FOR BeadSort_J = 0 TO MAX BeadSort_Sum = 0 FOR BeadSort_I = 0 TO (finish - start) BeadSort_Sum = BeadSort_Sum + beads(BeadSort_I, BeadSort_J) beads(BeadSort_I, BeadSort_J) = 0 NEXT FOR BeadSort_I = (finish - start) - BeadSort_Sum TO (finish - start) beads(BeadSort_I, BeadSort_J) = 1 NEXT NEXT FOR BeadSort_I = 0 TO (finish - start) BeadSort_J = 0 WHILE BeadSort_J < MAX AND beads(BeadSort_I, BeadSort_J) BeadSort_J = BeadSort_J + 1 WEND CGSortLibArray(BeadSort_I) = BeadSort_J NEXT ELSE FOR BeadSort_J = MAX TO 0 STEP -1 BeadSort_Sum = 0 FOR I = 0 TO (finish - start) BeadSort_Sum = BeadSort_Sum + beads(I, BeadSort_J) beads(I, BeadSort_J) = 0 NEXT FOR I = (finish - start) TO (finish - start) - BeadSort_Sum STEP -1 beads(I, BeadSort_J) = 1 NEXT NEXT FOR BeadSort_I = 0 TO (finish - start) BeadSort_J = 0 WHILE BeadSort_J < MAX AND beads(BeadSort_I, BeadSort_J) BeadSort_J = BeadSort_J + 1 WEND CGSortLibArray(finish - BeadSort_I) = BeadSort_J NEXT END IF END SUB  
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
#JavaScript
JavaScript
  // Node 5.4.1 tested implementation (ES6) "use strict";   let arr = [4, 9, 0, 3, 1, 5]; let isSorted = true; while (isSorted){ for (let i = 0; i< arr.length - 1;i++){ if (arr[i] > arr[i + 1]) { let temp = arr[i]; arr[i] = arr[i + 1]; arr[i+1] = temp; isSorted = true; } }   if (!isSorted) break;   isSorted = false;   for (let j = arr.length - 1; j > 0; j--){ if (arr[j-1] > arr[j]) { let temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; isSorted = true; } } } console.log(arr);   }
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
#Ada
Ada
with Knights_Tour, Ada.Text_IO, Ada.Command_Line;   procedure Holy_Knight is   Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); package KT is new Knights_Tour(Size => Size); Board: KT.Tour := (others => (others => Natural'Last));   Start_X, Start_Y: KT.Index:= 1; -- default start place (1,1) S: String(KT.Index); I: Positive := KT.Index'First; begin -- read the board from standard input while not Ada.Text_IO.End_Of_File and I <= Size loop S := Ada.Text_IO.Get_Line; for J in KT.Index loop if S(J) = ' ' or S(J) = '-' then Board(I,J) := Natural'Last; elsif S(J) = '1' then Start_X := I; Start_Y := J; Board(I,J) := 1; else Board(I,J) := 0; end if; end loop; I := I + 1; end loop;   -- print the board Ada.Text_IO.Put_Line("Start Configuration (Length:" & Natural'Image(KT.Count_Moves(Board)) & "):"); KT.Tour_IO(Board, Width => 1); Ada.Text_IO.New_Line;   -- search for the tour and print it Ada.Text_IO.Put_Line("Tour:"); KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); end Holy_Knight;
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
#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] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; }   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 ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } }   int wid, hei, max, dx[8], dy[8]; node* arr; };   int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; 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/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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program compositeSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*******************************************/ /* Structures */ /********************************************/ /* city structure */ .struct 0 city_name: @ .struct city_name + 4 city_habitants: @ .struct city_habitants + 4 city_end: /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Name : @ number habitants : @ \n" szMessSortHab: .asciz "Sort table for number of habitants :\n" szMessSortName: .asciz "Sort table for name of city :\n" szCarriageReturn: .asciz "\n"   // cities name szCeret: .asciz "Ceret" szMaureillas: .asciz "Maureillas" szTaillet: .asciz "Taillet" szReynes: .asciz "Reynes" szVives: .asciz "Vivés" szBoulou: .asciz "Le Boulou" szSaintJean: .asciz "Saint Jean Pla de Corts" szCluses: .asciz "Les Cluses" szAlbere: .asciz "L'Albère" szPerthus: .asciz "Le Perthus" .align 4   TableCities: .int szCluses @ address name string .int 251 @ number of habitants .int szCeret .int 7705 .int szMaureillas .int 2596 .int szBoulou .int 5554 .int szSaintJean .int 2153 .int szAlbere .int 83 .int szVives .int 174 .int szTaillet .int 115 .int szPerthus .int 586 .int szReynes .int 1354 .equ NBELEMENTS, (. - TableCities) / city_end /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   ldr r0,iAdrszMessSortHab bl affichageMess   ldr r0,iAdrTableCities @ address city table mov r1,#0 @ not use in routine mov r2,#NBELEMENTS @ number of élements mov r3,#city_habitants @ sort by number habitants mov r4,#'N' @ Alphanumeric bl shellSort ldr r0,iAdrTableCities @ address number table bl displayTable   ldr r0,iAdrszMessSortName bl affichageMess   ldr r0,iAdrTableCities @ address city table mov r1,#0 @ not use in routine mov r2,#NBELEMENTS @ number of élements mov r3,#city_name @ sort by name mov r4,#'A' @ Alphanumeric bl shellSort ldr r0,iAdrTableCities @ address number table bl displayTable   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrTableCities: .int TableCities iAdrszMessSortHab: .int szMessSortHab iAdrszMessSortName: .int szMessSortName /***************************************************/ /* shell Sort */ /***************************************************/   /* r0 contains the address of table */ /* r1 contains the first element but not use !! */ /* this routine use first element at index zero !!! */ /* r2 contains the number of element */ /* r3 contains the offset of sort zone */ /* r4 contains type of sort zone N = numeric A = alphanumeric */ shellSort: push {r0-r12,lr} @ save registers sub sp,#city_end @ reserve area on stack mov fp,sp @ frame pointer = stack mov r8,r3 @ save offser area sort mov r9,r4 @ save type sort mov r7,#city_end @ element size //vidregtit debut sub r12,r2,#1 @ index last item mov r6,r12 @ init gap = last item 1: @ start loop 1 lsrs r6,#1 @ gap = gap / 2 beq 100f @ if gap = 0 -> end mov r3,r6 @ init loop indice 1 2: @ start loop 2 mul r1,r3,r7 @ offset élement mov r2,fp @ save on stack bl saveElement add r1,r8 @ + offset sort zone ldr r4,[r0,r1] @ load first value mov r5,r3 @ init loop indice 2 3: @ start loop 3 cmp r5,r6 @ indice < gap blt 8f @ yes -> end loop 2 sub r10,r5,r6 @ index = indice - gap mul r1,r10,r7 @ offset élement add r10,r1,r8 @ + offset sort zone ldr r2,[r0,r10] @ load second value push {r3,r5} @ save registrars because not enought register cmp r9,#'A' @ sort area alapha ? beq 4f @ yes cmp r4,r2 @ else compare numeric values bge 7f @ highter b 6f @ lower 4: @ compare area alphanumeric mov r10,#0 @ counter 5: ldrb r3,[r4,r10] @ byte string 1 ldrb r5,[r2,r10] @ byte string 2 cmp r3,r5 bgt 7f blt 6f   cmp r3,#0 @ end string 1 beq 7f @ ens comparaison add r10,r10,#1 @ else add 1 in counter b 5b @ and loop   6: pop {r3,r5} @ restaur registers mul r2,r5,r7 @ offset élement bl copyElement @ copy element r1 to element r2 sub r5,r6 @ indice = indice - gap b 3b @ and loop 7: pop {r3,r5} 8: @ end loop 3 mul r1,r5,r7 @ offset destination élement mov r2,fp @ restaur element in table bl restaurElement add r3,#1 @ increment indice 1 cmp r3,r12 @ end ? ble 2b @ no -> loop 2 b 1b @ yes loop for new gap   100: @ end function add sp,#city_end pop {r0-r12,lr} @ restaur registers bx lr @ return /******************************************************************/ /* copy table element */ /******************************************************************/ /* r0 contains the address of table */ /* r1 offset origin element */ /* r2 offset destination element */ copyElement: push {r0-r4,lr} @ save registers //vidregtit copy mov r3,#0 add r1,r0 add r2,r0 1: ldrb r4,[r1,r3] strb r4,[r2,r3] add r3,#1 cmp r3,#city_end blt 1b 100: pop {r0-r4,lr} bx lr /******************************************************************/ /* save element */ /******************************************************************/ /* r0 contains the address of table */ /* r1 offset origin element */ /* r2 address destination */ saveElement: push {r0-r4,lr} @ save registers mov r3,#0 add r1,r0 1: ldrb r4,[r1,r3] strb r4,[r2,r3] add r3,#1 cmp r3,#city_end blt 1b 100: pop {r0-r4,lr} bx lr /******************************************************************/ /* restaur element */ /******************************************************************/ /* r0 contains the address of table */ /* r1 offset destination element */ /* r2 address origine */ restaurElement: push {r0-r4,lr} @ save registers mov r3,#0 add r1,r0 1: ldrb r4,[r2,r3] strb r4,[r1,r3] add r3,#1 cmp r3,#city_end blt 1b 100: pop {r0-r4,lr} bx lr /******************************************************************/ /* Display table elements */ /******************************************************************/ /* r0 contains the address of table */ displayTable: push {r0-r6,lr} @ save registers mov r2,r0 @ table address mov r3,#0 mov r6,#city_end 1: @ loop display table mul r4,r3,r6 add r4,#city_name ldr r1,[r2,r4] ldr r0,iAdrsMessResult bl strInsertAtCharInc @ put name in message mov r5,r0 @ save address of new message mul r4,r3,r6 add r4,#city_habitants @ and load value ldr r0,[r2,r4] ldr r1,iAdrsZoneConv bl conversion10 @ call decimal conversion mov r0,r5 ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message add r3,#1 cmp r3,#NBELEMENTS - 1 ble 1b ldr r0,iAdrszCarriageReturn bl affichageMess 100: pop {r0-r6,lr} bx lr iAdrsZoneConv: .int sZoneConv   /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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.)
#Quackery
Quackery
[ 2dup peek 1+ unrot poke ] is [1+] ( [ n --> [ )   [ 1+ dip tuck - rot 0 swap of swap rot witheach [ over + rot swap [1+] swap ] negate swap [] swap witheach [ dip [ over i^ + ] of join ] nip ] is csort ( [ n n --> [ )   [] 15 times [ 10 random 10 + join ]   dup say "Before: " echo cr 10 19 csort say "After: " echo
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.)
#R
R
counting_sort <- function(arr, minval, maxval) { r <- arr z <- 1 for(i in minval:maxval) { cnt = sum(arr == i) while(cnt > 0) { r[z] = i z <- z + 1 cnt <- cnt - 1 } } r }   # 140+1 instead of 140, since random numbers generated # by runif are always less than the given maximum; # floor(a number at most 140.9999...) is 140 ages <- floor(runif(100, 0, 140+1)) sorted <- counting_sort(ages, 0, 140) print(sorted)
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).
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program noconnpuzzle.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ NBBOX, 8 .equ POSA, 5   /*********************************/ /* Initialized data */ /*********************************/ .data sMessDeb: .ascii "a=" sMessValeur_a: .fill 11, 1, ' ' @ size => 11 .ascii "b=" sMessValeur_b: .fill 11, 1, ' ' @ size => 11 .ascii "c=" sMessValeur_c: .fill 11, 1, ' ' @ size => 11 .ascii "d=" sMessValeur_d: .fill 11, 1, ' ' @ size => 11 .ascii "\n" .ascii "e=" sMessValeur_e: .fill 11, 1, ' ' @ size => 11 .ascii "f=" sMessValeur_f: .fill 11, 1, ' ' @ size => 11 .ascii "g=" sMessValeur_g: .fill 11, 1, ' ' @ size => 11 .ascii "h=" sMessValeur_h: .fill 11, 1, ' ' @ size => 11   szCarriageReturn: .asciz "\n************************\n"   szMessLine1: .asciz " \n" szMessLine2: .asciz " /|\\ /|\\ \n" szMessLine3: .asciz " / | X | \\ \n" szMessLine4: .asciz " / |/ \\| \\ \n" szMessLine5: .asciz " - - | - \n" szMessLine6: .asciz " \\ |\\ /| / \n" szMessLine7: .asciz " \\ | X | / \n" szMessLine8: .asciz " \\|/ \\|/ \n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 iValues_a: .skip 4 * NBBOX iValues_b: .skip 4 * NBBOX - 1 iValues_c: .skip 4 * NBBOX - 2 iValues_d: .skip 4 * NBBOX - 3 iValues_e: .skip 4 * NBBOX - 4 iValues_f: .skip 4 * NBBOX - 5 iValues_g: .skip 4 * NBBOX - 6 iValues_h: .skip 4 * NBBOX - 7 sConvValue: .skip 12 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program mov r0,#1 mov r1,#8 bl searchPb   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn   /******************************************************************/ /* search problem unique solution */ /******************************************************************/ /* r0 contains start digit */ /* r1 contains end digit */ searchPb: push {r0-r12,lr} @ save registers @ init ldr r3,iAdriValues_a @ area value a mov r4,#0 1: @ loop init value a str r0,[r3,r4,lsl #2] add r4,#1 add r0,#1 cmp r0,r1 ble 1b   mov r12,#-1 2: add r12,#1 @ increment indice a cmp r12,#NBBOX-1 bgt 90f ldr r0,iAdriValues_a @ area value a ldr r1,iAdriValues_b @ area value b mov r2,r12 @ indice a mov r3,#NBBOX @ number of origin values bl prepValues mov r11,#-1 3: add r11,#1 @ increment indice b cmp r11,#NBBOX - 2 bgt 2b ldr r0,iAdriValues_b @ area value b ldr r1,iAdriValues_c @ area value c mov r2,r11 @ indice b mov r3,#NBBOX -1 @ number of origin values bl prepValues mov r10,#-1 4: add r10,#1 cmp r10,#NBBOX - 3 bgt 3b ldr r0,iAdriValues_a ldr r0,[r0,r12,lsl #2] ldr r1,iAdriValues_c ldr r1,[r1,r10,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 4b ldr r0,iAdriValues_c ldr r1,iAdriValues_d mov r2,r10 mov r3,#NBBOX - 2 bl prepValues mov r9,#-1 5: add r9,#1 cmp r9,#NBBOX - 4 bgt 4b @ control d / a b c ldr r0,iAdriValues_d ldr r0,[r0,r9,lsl #2] ldr r1,iAdriValues_a ldr r1,[r1,r12,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 5b ldr r1,iAdriValues_b ldr r1,[r1,r11,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 5b ldr r1,iAdriValues_c ldr r1,[r1,r10,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 5b   ldr r0,iAdriValues_d ldr r1,iAdriValues_e mov r2,r9 mov r3,#NBBOX - 3 bl prepValues mov r8,#-1 6: add r8,#1 cmp r8,#NBBOX - 5 bgt 5b @ control e / a b d ldr r0,iAdriValues_e ldr r0,[r0,r8,lsl #2] ldr r1,iAdriValues_a ldr r1,[r1,r12,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 6b ldr r1,iAdriValues_b ldr r1,[r1,r11,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 6b ldr r1,iAdriValues_d ldr r1,[r1,r9,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 6b   ldr r0,iAdriValues_e ldr r1,iAdriValues_f mov r2,r8 mov r3,#NBBOX - 4 bl prepValues mov r7,#-1 7: add r7,#1 cmp r7,#NBBOX - 6 bgt 6b @ control f / b e ldr r0,iAdriValues_f ldr r0,[r0,r7,lsl #2] ldr r1,iAdriValues_b ldr r1,[r1,r11,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 7b ldr r1,iAdriValues_e ldr r1,[r1,r8,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 7b   ldr r0,iAdriValues_f ldr r1,iAdriValues_g mov r2,r7 mov r3,#NBBOX - 5 bl prepValues mov r6,#-1 8: add r6,#1 cmp r6,#NBBOX - 7 bgt 7b @ control g / c d e ldr r0,iAdriValues_g ldr r0,[r0,r6,lsl #2] ldr r1,iAdriValues_c ldr r1,[r1,r10,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 8b ldr r1,iAdriValues_d ldr r1,[r1,r9,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 8b ldr r1,iAdriValues_e ldr r1,[r1,r8,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 8b ldr r0,iAdriValues_g ldr r1,iAdriValues_h mov r2,r6 mov r3,#NBBOX - 6 bl prepValues mov r5,#-1 9: add r5,#1 cmp r5,#NBBOX - 8 bgt 8b @ control h / d e f ldr r0,iAdriValues_h ldr r0,[r0,r5,lsl #2] ldr r1,iAdriValues_d ldr r1,[r1,r9,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 9b ldr r1,iAdriValues_e ldr r1,[r1,r8,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 9b ldr r1,iAdriValues_f ldr r1,[r1,r7,lsl #2] subs r2,r1,r0 mvnlt r2,r2 addlt r2,#1 cmp r2,#1 beq 9b @ solution ok display text ldr r0,iAdriValues_a ldr r0,[r0,r12,lsl #2] ldr r1,iAdrsMessValeur_a bl conversion10 ldr r0,iAdriValues_b ldr r0,[r0,r11,lsl #2] ldr r1,iAdrsMessValeur_b bl conversion10 ldr r0,iAdriValues_c ldr r0,[r0,r10,lsl #2] ldr r1,iAdrsMessValeur_c bl conversion10 ldr r0,iAdriValues_d ldr r0,[r0,r9,lsl #2] ldr r1,iAdrsMessValeur_d bl conversion10 ldr r0,iAdriValues_e ldr r0,[r0,r8,lsl #2] ldr r1,iAdrsMessValeur_e bl conversion10 ldr r0,iAdriValues_f ldr r0,[r0,r7,lsl #2] ldr r1,iAdrsMessValeur_f bl conversion10 ldr r0,iAdriValues_g ldr r0,[r0,r6,lsl #2] ldr r1,iAdrsMessValeur_g bl conversion10 ldr r0,iAdriValues_h ldr r0,[r0,r5,lsl #2] ldr r1,iAdrsMessValeur_h bl conversion10 ldr r0,iAdrsMessDeb bl affichageMess   @ display design ldr r0,iAdriValues_a ldr r0,[r0,r12,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine1 strb r2,[r0,#POSA] ldr r0,iAdriValues_b ldr r0,[r0,r11,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine1 strb r2,[r0,#POSA+4] bl affichageMess ldr r0,iAdrszMessLine2 bl affichageMess ldr r0,iAdrszMessLine3 bl affichageMess ldr r0,iAdrszMessLine4 bl affichageMess ldr r0,iAdriValues_c ldr r0,[r0,r10,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine5 strb r2,[r0,#POSA-4] ldr r0,iAdriValues_d ldr r0,[r0,r9,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine5 strb r2,[r0,#POSA] ldr r0,iAdriValues_e ldr r0,[r0,r8,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine5 strb r2,[r0,#POSA+4] ldr r0,iAdriValues_f ldr r0,[r0,r7,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine5 strb r2,[r0,#POSA+8] bl affichageMess ldr r0,iAdrszMessLine6 bl affichageMess ldr r0,iAdrszMessLine7 bl affichageMess ldr r0,iAdrszMessLine8 bl affichageMess ldr r0,iAdriValues_g ldr r0,[r0,r6,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine1 strb r2,[r0,#POSA] ldr r0,iAdriValues_h ldr r0,[r0,r5,lsl #2] ldr r1,iAdrsConvValue bl conversion10 ldrb r2,[r1] ldr r0,iAdrszMessLine1 strb r2,[r0,#POSA+4] bl affichageMess   //b 9b @ loop for other solution 90:   100: pop {r0-r12,lr} @ restaur registers bx lr @return iAdriValues_a: .int iValues_a iAdriValues_b: .int iValues_b iAdriValues_c: .int iValues_c iAdriValues_d: .int iValues_d iAdriValues_e: .int iValues_e iAdriValues_f: .int iValues_f iAdriValues_g: .int iValues_g iAdriValues_h: .int iValues_h   iAdrsMessValeur_a: .int sMessValeur_a iAdrsMessValeur_b: .int sMessValeur_b iAdrsMessValeur_c: .int sMessValeur_c iAdrsMessValeur_d: .int sMessValeur_d iAdrsMessValeur_e: .int sMessValeur_e iAdrsMessValeur_f: .int sMessValeur_f iAdrsMessValeur_g: .int sMessValeur_g iAdrsMessValeur_h: .int sMessValeur_h iAdrsMessDeb: .int sMessDeb   iAdrsConvValue: .int sConvValue iAdrszMessLine1: .int szMessLine1 iAdrszMessLine2: .int szMessLine2 iAdrszMessLine3: .int szMessLine3 iAdrszMessLine4: .int szMessLine4 iAdrszMessLine5: .int szMessLine5 iAdrszMessLine6: .int szMessLine6 iAdrszMessLine7: .int szMessLine7 iAdrszMessLine8: .int szMessLine8 /******************************************************************/ /* copy value area and substract value of indice */ /******************************************************************/ /* r0 contains the address of values origin */ /* r1 contains the address of values destination */ /* r2 contains value indice to substract */ /* r3 contains origin values number */ prepValues: push {r1-r6,lr} @ save registres mov r4,#0 @ indice origin value mov r5,#0 @ indice destination value 1: cmp r4,r2 @ substract indice ? beq 2f @ yes -> jump ldr r6,[r0,r4,lsl #2] @ no -> copy value str r6,[r1,r5,lsl #2] add r5,#1 @ increment destination indice 2: add r4,#1 @ increment origin indice cmp r4,r3 @ end ? blt 1b 100: pop {r1-r6,lr} @ restaur registres bx lr @return /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL 1: @ start loop bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ else previous position bne 1b @ and loop @ and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b @ and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD    
http://rosettacode.org/wiki/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
#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 := [] nCells := maxCols := 0 every line := !&input do { put(p,[: gencells(line) :]) maxCols <:= *p[-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["_"] := 0; 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, puzzle[loc.r,loc.c] = (val|0)); end method visit(r,c); return (/best, validPos(r,c), Pos(r,c)); end   method validPos(r,c) v := val+1 # number we're looking for xv := puzzle[r,c] | fail if (xv ~= 0) & (xv != v) then fail if xv = (0|v) then { 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-1,loc.c) , self, val) # North QMouse(puzzle, visit(loc.r, loc.c+1), self, val) # East QMouse(puzzle, visit(loc.r+1,loc.c), self, val) # South QMouse(puzzle, visit(loc.r, loc.c-1), self, val) # West end
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.
#Beads
Beads
beads 1 program 'Sort an integer array' calc main_init var arr = [4, 1, 2, -1, 3, 0, 2] var newarr : array of num loop across:arr sort:val count:c val:v newarr[c] = v
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.
#Befunge
Befunge
v > 543** >  :#v_ $&>  :#v_ 1 > :0g >  :#v_ $ 1+: 543** `! #v_ 25*,@ ^-1p0\0:< ^-1 p0\+1 g0:&< ^-1\.:\< ^ <
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
#Common_Lisp
Common Lisp
(defun oid->list (oid) (loop for start = 0 then (1+ pos) for pos = (position #\. oid :start start) collect (parse-integer oid :start start :end pos) while pos))   (defun list< (list1 list2) (loop for e1 in list1 for e2 in list2 do (cond ((< e1 e2) (return t)) ((> e1 e2) (return nil))) finally (return (< (length list1) (length list2)))))   (defun sort-oids (oids) (sort oids #'list< :key #'oid->list))   (defun main () (let ((oids (list "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"))) (dolist (oid (sort-oids oids)) (write-line oid))))
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
#Elixir
Elixir
defmodule Sort_by_OID do def numbers(list) do Enum.sort_by(list, fn oid -> String.split(oid, ".") |> Enum.map(&String.to_integer/1) end) end end   ~w[ 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 ] |> Sort_by_OID.numbers |> Enum.each(fn oid -> IO.puts oid end)
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#Erlang
Erlang
  -module( sort_disjoint ).   -export( [sublist/2, task/0] ).   sublist( Values, Indices ) -> Sorted_indices = lists:sort( Indices ), Values_indexes = lists:seq( 1, erlang:length(Values) ), {[], [], Indices_values} = lists:foldl( fun indices_values/2, {Values, Sorted_indices, []}, Values_indexes ), Sorted_indices_values = lists:zip( Sorted_indices, lists:sort(Indices_values) ), {Sorted_values, {[], []}} = lists:mapfoldl( fun merge/2, {Values, Sorted_indices_values}, Values_indexes ), Sorted_values.   task() -> sublist( [7, 6, 5, 4, 3, 2, 1, 0], [7, 2, 8] ).       indices_values( Index, {[H | Values], [Index | Indices], Indices_values} ) -> {Values, Indices, [H | Indices_values]}; indices_values( _Index, {[_H | Values], Indices, Indices_values} ) -> {Values, Indices, Indices_values}.   merge( Index, {[_H | Values], [{Index, Value} | Sorted_indices_values]} ) -> {Value, {Values, Sorted_indices_values}}; merge( _Index, {[H | Values], Sorted_indices_values} ) -> {H, {Values, Sorted_indices_values}}.  
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).
#OpenEdge.2FProgress
OpenEdge/Progress
DEFINE TEMP-TABLE tt FIELD country AS CHAR FORMAT 'x(2)' FIELD city AS CHAR FORMAT 'x(16)' .   DEFINE VARIABLE cc AS CHARACTER EXTENT 2.   CREATE tt. ASSIGN tt.country = 'UK' tt.city = 'London'. CREATE tt. ASSIGN tt.country = 'US' tt.city = 'New York'. CREATE tt. ASSIGN tt.country = 'US' tt.city = 'Birmingham'. CREATE tt. ASSIGN tt.country = 'UK' tt.city = 'Birmingham'.   cc[1] = 'by country~n~n'. FOR EACH tt BY tt.country BY ROWID( tt ): cc[1] = cc[1] + tt.country + '~t' + tt.city + '~n'. END.   cc[2] = 'by city~n~n'. FOR EACH tt BY tt.city BY ROWID( tt ): cc[2] = cc[2] + tt.country + '~t' + tt.city + '~n'. END.   MESSAGE cc[1] SKIP(1) cc[2] VIEW-AS ALERT-BOX.
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).
#Oz
Oz
declare Cities = ['UK'#'London' 'US'#'New York' 'US'#'Birmingham' 'UK'#'Birmingham'] in %% sort by city; stable because '=<' is reflexiv {Show {Sort Cities fun {$ A B} A.2 =< B.2 end}}   %% sort by country; NOT stable because '<' is not reflexiv {Show {Sort Cities fun {$ A B} A.1 < B.1 end}}
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{x, y, z} = Sort[{x, y, z}]
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#min
min
(=c =b =a (a -> b -> c ->) => '> sort -> c @ b @ a @) :sort3   "lions, tigers, and" :x "bears, oh my!" :y "(from the \"Wizard of OZ\")" :z   'x 'y 'z sort3 x puts! y puts! z puts!   77444 :x -12 :y 0 :z   'x 'y 'z sort3 x puts! y puts! z puts!
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.
#Haskell
Haskell
import Data.Char (toLower) import Data.List (sortBy) import Data.Ord (comparing)   -------------------- CUSTOM COMPARATORS ------------------   lengthThenAZ :: String -> String -> Ordering lengthThenAZ = comparing length <> comparing (fmap toLower)   descLengthThenAZ :: String -> String -> Ordering descLengthThenAZ = flip (comparing length) <> comparing (fmap toLower)   --------------------------- TEST ------------------------- main :: IO () main = mapM_ putStrLn ( fmap unlines ( [sortBy] <*> [lengthThenAZ, descLengthThenAZ] <*> [ [ "Here", "are", "some", "sample", "strings", "to", "be", "sorted" ] ] ) )
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#Rust
Rust
fn comb_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); let mut gap = len; let mut swapped = true; while gap > 1 || swapped { gap = (4 * gap) / 5; if gap < 1 { gap = 1; } let mut i = 0; swapped = false; while i + gap < len { if a[i] > a[i + gap] { a.swap(i, i + gap); swapped = true; } i += 1; } } }   fn main() { let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]; println!("before: {:?}", v); comb_sort(&mut v); println!("after: {:?}", v); }
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#PureBasic
PureBasic
Procedure KnuthShuffle (Array a(1)) Protected i, Size = ArraySize(a()) For i = 0 To Size Swap a(i), a(Random(Size)) Next EndProcedure   Procedure isSorted(Array a(1)) Protected i, Size = ArraySize(a()) For i = 1 To Size If a(i) < a(i - 1) ProcedureReturn #False EndIf Next ProcedureReturn #True EndProcedure   Procedure BogoSort(Array a(1)) Protected Size = ArraySize(a()) + 1, iter   While Not isSorted(a()) iter + 1 KnuthShuffle(a()) Wend MessageRequester("Results","Array of " + Str(Size) + " integers required " + Str(iter) + " shuffles To SORT.") EndProcedure   Dim b(10) For i = 0 To 10 b(i) = Random(100) Next   BogoSort(b())
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Dyalect
Dyalect
func bubbleSort(list) { var done = false while !done { done = true for i in 1..(list.Length()-1) { if list[i - 1] > list[i] { var x = list[i] list[i] = list[i - 1] list[i - 1] = x done = false } } } }   var xs = [3,1,5,4,2,6] bubbleSort(xs) print(xs)
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
gnomeSort[list_]:=Module[{i=2,j=3}, While[ i<=Length[[list]], If[ list[[i-1]]<=list[[i]], i=j; j++;, list[[i-1;;i]]=list[[i;;i-1]];i--;]; If[i==1,i=j;j++;] ]]
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Racket
Racket
  #lang racket (require rackunit)   (define (columns lst) (match (filter (λ (l) (not (empty? l))) lst) ['() '()] [l (cons (map car l) (columns (map cdr l)))]))   (define (bead-sort lst) (map length (columns (columns (map (λ (n) (make-list n 1)) lst)))))   ;; unit test (check-equal? (bead-sort '(5 3 1 7 4 1 1)) '(7 5 4 3 1 1 1))  
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Raku
Raku
# routine cribbed from List::Utils; sub transpose(@list is copy) { gather { while @list { my @heads; if @list[0] !~~ Positional { @heads = @list.shift; } else { @heads = @list.map({$_.shift unless $_ ~~ []}); } @list = @list.map({$_ unless $_ ~~ []}); take [@heads]; } } }   sub beadsort(@l) { (transpose(transpose(map {[1 xx $_]}, @l))).map(*.elems); }   my @list = 2,1,3,5; say beadsort(@list).perl;
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
#jq
jq
# In case your jq does not have "until" defined: def until(cond; next): def _until: if cond then . else (next|_until) end; _until;
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
#ALGOL_68
ALGOL 68
# directions for moves # INT nne = 1, ne = 2, se = 3, sse = 4; INT ssw = 5, sw = 6, nw = 7, nnw = 8;   INT lowest move = nne; INT highest move = nnw;   # the vertical position changes of the moves # []INT offset v = ( -2, -1, 1, 2, 2, 1, -1, -2 ); # the horizontal position changes of the moves # []INT offset h = ( 1, 2, 2, 1, -1, -2, -2, -1 );   MODE SQUARE = STRUCT( INT move # the number of the move that caused # # the knight to reach this square # , INT direction # the direction of the move that # # brought the knight here - one of # # nne, ne, se, sse, ssw, sw, nw or # # nnw # ); # get the size of the board - must be between 4 and 8 # INT board size = 8; # the board # [ board size, board size ]SQUARE board; # starting position # INT start row := 1; INT start col := 1; # the tour will be complete when we have made as many moves # # as there are free squares in the initial board # INT final move := 0;   # initialise the board setting the free squares from the supplied pttern # # the pattern has the rows in revers order # PROC initialise board = ( []STRING pattern )VOID: BEGIN INT pattern row := UPB board; FOR row FROM 1 LWB board TO 1 UPB board DO FOR col FROM 2 LWB board TO 2 UPB board DO IF pattern[ pattern row ][ col ] = "-" THEN # can't use this square # board[ row, col ] := ( -1, -1 ) ELSE # available square # board[ row, col ] := ( 0, 0 ); final move +:= 1; IF pattern[ pattern row ][ col ] = "1" THEN # have the start position # start row := row; start col := col FI FI OD; pattern row -:= 1 OD END; # initialise board # # statistics # INT iterations := 0; INT backtracks := 0;   # prints the board # PROC print tour = VOID: BEGIN # format "number" into at least two characters # PROC n2 = ( INT number )STRING: IF number < 0 THEN " -" ELIF number < 10 AND number >= 0 THEN " " + whole( number, 0 ) ELSE whole( number, 0 ) FI; # n2 # print( ( " a b c d e f g h", newline ) ); print( ( " ________________________", newline ) ); FOR row FROM 1 UPB board BY -1 TO 1 LWB board DO print( ( n2( row ) ) ); print( ( "|" ) );   FOR col FROM 2 LWB board TO 2 UPB board DO print( ( " " ) ); print( ( n2( move OF board[ row, col ] ) ) ) OD; print( ( newline ) ) OD END; # print tour #   # update the board to the first knight's tour found starting from # # "start row" and "start col". # # return TRUE if one was found, FALSE otherwise # PROC find tour = BOOL: BEGIN   BOOL result := TRUE; INT move number := 1; INT row := start row; INT col := start col; INT direction := lowest move - 1; # the first move is to place the knight on the starting square # board[ row, col ] := ( move number, lowest move - 1 ); # attempt to find a sequence of moves that will reach each square once # WHILE move number < final move AND result DO IF direction < highest move THEN # try the next move from this position # direction +:= 1; INT new row = row + offset v[ direction ]; INT new col = col + offset h[ direction ]; IF new row <= 1 UPB board AND new row >= 1 LWB board AND new col <= 2 UPB board AND new col >= 2 LWB board THEN # the move is legal, check the new square is unused # IF move OF board[ new row, new col ] = 0 THEN # can move here # iterations +:= 1; row := new row; col := new col; move number +:= 1; board[ row, col ] := ( move number, direction ); direction := lowest move - 1 FI FI ELSE # no more moves from this position - backtrack # IF move number = 1 THEN # at the starting position - no solution # result := FALSE ELSE # not at the starting position - undo the latest move # backtracks +:= 1; move number -:= 1; INT curr row := row; INT curr col := col; row -:= offset v[ direction OF board[ curr row, curr col ] ]; col -:= offset h[ direction OF board[ curr row, curr col ] ]; # determine which direction to try next # direction := direction OF board[ curr row, curr col ]; # reset the square we just backtracked from # board[ curr row, curr col ] := ( 0, 0 ) FI FI OD; result END; # find tour #   main:( initialise board( ( "-000----" , "-0-00---" , "-0000000" , "000--0-0" , "0-0--000" , "1000000-" , "--00-0--" , "---000--" ) ); IF find tour THEN # found a solution # print tour ELSE # couldn't find a solution # print( ( "Solution not found", newline ) ) FI; print( ( iterations, " iterations, ", backtracks, " backtracks", newline ) ) )
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
#D
D
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons;     struct HopidoPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max } // Special Cell values.   // Neighbors, [shift row, shift column]. private static immutable int[2][8] shifts = [[-2, -2], [2, -2], [-2, 2], [2, 2], [ 0, -3], [0, 3], [-3, 0], [3, 0]];   private immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private /*immutable*/ const InputCell[] flatPuzzle; private Cell[] grid; // Flattened mutable game grid.   @disable this();     this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular.   // Has at least one start point. assert(rawPuzzle.join.representation.canFind(InputCell.available)); } body { //immutable puzzle = rawPuzzle.to!(InputCell[][]); immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]);   gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join; nAvailableCells = flatPuzzle.representation.count!(ic => ic == InputCell.available);   grid = flatPuzzle .representation .map!(ic => ic == InputCell.available ? unknownCell : unavailableCell) .array; }     Nullable!(string[][]) solve() pure /*nothrow*/ @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { // Try all possible start positions. foreach (immutable r; 0 .. gridHeight) { foreach (immutable c; 0 .. gridWidth) { immutable pos = r * gridWidth + c; if (grid[pos] == unknownCell) { immutable Cell startCell = 1; // To lay the first cell value. grid[pos] = startCell; // Try. if (search(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) //.map!({p, c} => ... .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(gridWidth) .array; return typeof(return)(result); } grid[pos] = unknownCell; // Restore. } } }   return typeof(return)(); }     private bool search(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; // One solution found.   foreach (immutable sh; shifts) { immutable r2 = r + sh[0], c2 = c + sh[1], pos = r2 * gridWidth + c2; // No need to test for >= 0 because uint wraps around. if (c2 < gridWidth && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; // Try. if (search(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; // Restore. } }   return false; } }     void main() @safe { // enum HopidoPuzzle to catch malformed puzzles at compile-time. enum puzzle = ".##.##. ####### ####### .#####. ..###.. ...#...".split.HopidoPuzzle;   immutable solution = puzzle.solve; // Solved at run-time. if (solution.isNull) writeln("No solution found."); else writefln("One solution:\n%(%-(%2s %)\n%)", solution); }
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.
#AutoHotkey
AutoHotkey
start: Gui, Add, ListView, r20 w200, 1|2 data = ( foo,53 joe,34 bar,23 )   Loop, parse, data, `n { stringsplit, row, A_LoopField, `, LV_Add(row, row1, row2) } LV_ModifyCol() ; Auto-size columns Gui, Show msgbox, sorting by column1 LV_ModifyCol(1, "sort") ; sort by first column msgbox, sorting by column2 LV_ModifyCol(2, "sort Integer") ; sort by second column numerically return   GuiClose: ExitApp
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.)
#Racket
Racket
  #lang racket   (define (counting-sort xs min max) (define ns (make-vector (+ max (- min) 1) 0)) (for ([x xs]) (vector-set! ns (- x min) (+ (vector-ref ns (- x min)) 1))) (for/fold ([i 0]) ([n ns] [x (in-naturals)]) (for ([j (in-range i (+ i n ))]) (vector-set! xs j (+ x min))) (+ i n)) xs)   (counting-sort (vector 0 9 3 8 1 -1 1 2 3 7 4) -1 10)