task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Java
Java
import java.util.Arrays;   public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); }   public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1);...
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Nim
Nim
import os, strutils   proc single(n: int) = sleep n echo n   proc main = var thr = newSeq[TThread[int]](paramCount()) for i,c in commandLineParams(): thr[i].createThread(single, c.parseInt) thr.joinThreads   main()
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Objeck
Objeck
  use System.Concurrency; use Collection;   bundle Default { class Item from Thread { @value : Int;   New(value : Int) { Parent(); @value := value; }   method : public : Run(param : System.Base) ~ Nil { Sleep(1000 * @value); @value->PrintLine(); } }   class SleepSort { ...
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Clojure
Clojure
(import 'java.util.ArrayList)   (defn arr-swap! [#^ArrayList arr i j] (let [t (.get arr i)] (doto arr (.set i (.get arr j)) (.set j t))))   (defn sel-sort! ([arr] (sel-sort! compare arr)) ([cmp #^ArrayList arr] (let [n (.size arr)] (letfn [(move-min! [start-i] (loop [i start-i] ...
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Common_Lisp
Common Lisp
(defun get-code (c) (case c ((#\B #\F #\P #\V) #\1) ((#\C #\G #\J #\K #\Q #\S #\X #\Z) #\2) ((#\D #\T) #\3) (#\L #\4) ((#\M #\N) #\5) (#\R #\6)))   (defun soundex (s) (if (zerop (length s)) "" (let* ((l (coerce (string-upcase s) 'list)) (o (list (first l)))) (l...
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#FreeBASIC
FreeBASIC
' version 21-10-2016 ' compile with: fbc -s console ' for boundry checks on array's compile with: fbc -s console -exx   Sub shellsort(s() As Long) ' sort from lower bound to the highter bound ' array's can have subscript range from -2147483648 to +2147483647 Dim As Long lb = LBound(s) Dim As Long ub = U...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#S-lang
S-lang
  % Just to demonstrate alternate ways of defining unicode: private variable spchrs = "\u{2581}\u{2582}\u{2583}\u{2584}\u{2585}\u{2586}\u{2587}\u{2588}"; private variable spchrs_alt = "▁▂▃▄▅▆▇█";   define sparkline(arrstr) { variable a = strtok(arrstr, " \t,"), alen = length(a), out = ""; a = atof(a); vari...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#Scala
Scala
def mkSparks( numStr:String ) : String = numStr.split( "[\\s,]+" ).map(_.toFloat) match { case v if v.isEmpty => "" case v if v.length == 1 => "\u2581" case v => (for( i <- v; s = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588".toCharArray; d = (v.max - v.min) / (s.length ...
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand 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 ...
#zkl
zkl
fcn strandSort(A){ //--> new list, A is cleared, should add A=A.copy() sublist:=List.createLong(A.len()); results:=List.createLong(A.len()); while(A){ sublist.clear(A.pop(0)); foreach i in (A.len() - 1){ if(A[i]>sublist[-1]) sublist.append(A.pop(i)); } results.merge(sublist); } res...
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Scala
Scala
object SMP extends App { private def checkMarriages(): Unit = if (check) println("Marriages are stable") else println("Marriages are unstable")   private def swap() { val girl1 = girls.head val girl2 = girls(1) val tmp = girl2 -> matches(girl1) ...
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Julia
Julia
stack = Int[] # [] @show push!(stack, 1) # [1] @show push!(stack, 2) # [1, 2] @show push!(stack, 3) # [1, 2, 3] @show pop!(stack) # 3 @show length(stack) # 2 @show empty!(stack) # [] @show isempty(stack) # true
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Julia
Julia
  immutable Spiral m::Int n::Int cmax::Int dir::Array{Array{Int,1},1} bdelta::Array{Array{Int,1},1} end   function Spiral(m::Int, n::Int) cmax = m*n dir = Array{Int,1}[[0,1], [1,0], [0,-1], [-1,0]] bdelta = Array{Int,1}[[0,0,0,1], [-1,0,0,0], [0,-1,0,0], [0,0,1,...
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#Elixir
Elixir
defmodule Sort do def radix_sort(list), do: radix_sort(list, 10)   def radix_sort([], _), do: [] def radix_sort(list, base) do max = abs(Enum.max_by(list, &abs(&1))) sorted = radix_sort(list, base, max, 1) {minus, plus} = Enum.partition(sorted, &(&1<0)) Enum.reverse(minus, plus) end   defp rad...
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#Fortran
Fortran
    SUBROUTINE VARRADIX(A , Siz)   ! ! No Copyright is exerted due to considerable prior art in the Public Domain. ! This Fortran version by Peter Kelly ~ peter.kelly@acm.org ! ! Permission is hereby granted, free of charge, to any person obtaining ! a copy of this software and associated documentation file...
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ada
Ada
----------------------------------------------------------------------- -- Generic Quick_Sort procedure ----------------------------------------------------------------------- generic type Element is private; type Index is (<>); type Element_Array is array(Index range <>) of Element; with function "<" (Left...
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Clojure
Clojure
  (defn patience-insert "Inserts a value into the sequence where each element is a stack. Comparison replaces the definition of less than. Uses the greedy strategy." [comparison sequence value] (lazy-seq (if (empty? sequence) `((~value)) ;; If there are no places to put the "card", make a new stack ...
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#11l
11l
F insertion_sort(&l) L(i) 1 .< l.len V j = i - 1 V key = l[i] L j >= 0 & l[j] > key l[j + 1] = l[j] j-- l[j + 1] = key   V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] insertion_sort(&arr) print(arr)
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Haskell
Haskell
import Control.Monad   permutationSort l = head [p | p <- permute l, sorted p]   sorted (e1 : e2 : r) = e1 <= e2 && sorted (e2 : r) sorted _ = True   permute = foldM (flip insert) []   insert e [] = return [e] insert e l@(h : t) = return (e : l) `mplus` do { t'...
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Icon_and_Unicon
Icon and Unicon
procedure do_permute(l, i, n) if i >= n then return l else suspend l[i to n] <-> l[i] & do_permute(l, i+1, n) end   procedure permute(l) suspend do_permute(l, 1, *l) end   procedure sorted(l) local i if (i := 2 to *l & l[i] >= l[i-1]) then return &fail else return 1 end   proce...
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.23
C#
  public static class PancakeSorter { public static void Sort<T>(List<T> list) where T : IComparable { if (list.Count < 2) { return; } int i, a, max_num_pos; for (i = list.Count; i > 1; i--) { max_num_pos = 0; for (a = 0; a < i;...
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Raku
Raku
$ Item @ Positional  % Associative & Callable
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#REXX
REXX
if a¬==b then say 'not equal' if a ¬== b then say 'not equal' if a ¬ = = b then say 'not equal' if a ¬ , = = b then say 'not equal'
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Ruby
Ruby
val n = 1 + 2
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#JavaScript
JavaScript
function stoogeSort (array, i, j) { if (j === undefined) { j = array.length - 1; }   if (i === undefined) { i = 0; }   if (array[j] < array[i]) { var aux = array[i]; array[i] = array[j]; array[j] = aux; }   if (j - i > 1) { var t = Math.floor((...
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main(int argc, char **argv) { NSOperationQueue *queue = [[NSOperationQueue alloc] init]; while (--argc) { int i = atoi(argv[argc]); [queue addOperationWithBlock: ^{ sleep(i); NSLog(@"%d\n", i); }]; } [queue waitUntil...
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Oforth
Oforth
import: parallel   : sleepSort(l) | ch n | Channel new ->ch l forEach: n [ #[ n dup 20 * sleep ch send drop ] & ] ListBuffer newSize(l size) #[ ch receive over add ] times(l size) ;
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#COBOL
COBOL
PERFORM E-SELECTION VARYING WB-IX-1 FROM 1 BY 1 UNTIL WB-IX-1 = WC-SIZE.   ...   E-SELECTION SECTION. E-000. SET WC-LOWEST TO WB-IX-1. ADD 1 WC-LOWEST GIVING WC-START   PERFORM F-PASS VARYING WB-IX-2 FROM WC-START BY 1 ...
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Crystal
Crystal
# version 0.21.1   def get_code(c : Char) case c when 'B', 'F', 'P', 'V' "1" when 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z' "2" when 'D', 'T' "3" when 'L' "4" when 'M', 'N' "5" when 'R' "6" when 'H', 'W' "-" else "" end end   def soundex(s : String) return "" if s ==...
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Go
Go
package main   import "fmt"   var a = []int{170, 45, 75, -90, -802, 24, 2, 66}   func main() { fmt.Println("before:", a) for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { for i := inc; i < len(a); i++ { j, temp := i, a[i] for ; j >= inc && a[j-inc] > temp; j -= inc { ...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "scanfile.s7i"; include "float.s7i"; include "utf8.s7i";   const func array float: readDataLine is func result var array float: data is 0 times 0.0; begin write("Numbers separated by anything: "); IN.bufferChar := getc(IN); skipSpace(IN); while IN.bufferCh...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#SenseTalk
SenseTalk
put sparklineGraph of "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" put sparklineGraph of "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5" put sparklineGraph of "0, 1, 19, 20" put sparklineGraph of "0, 999, 4000, 4999, 7000, 7999"   to handle sparklineGraph of input put each word delimited by " ," of input into numbers put the lowestValue of...
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: preferences is hash [string] array string; const type: engaged is hash [string] string;   const func integer: pos (in array string: area, in string: searched) is func result var integer: pos is 1; begin while pos <= length(area) and area[pos] <> searched do incr...
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#K
K
stack:() push:{stack::x,stack} pop:{r:*stack;stack::1_ stack;r} empty:{0=#stack}   /example: stack:() push 3 stack ,3 push 5 stack 5 3 pop[] 5 stack ,3 empty[] 0 pop[] 3 stack !0 empty[] 1  
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Kotlin
Kotlin
// version 1.1.3   typealias Vector = IntArray typealias Matrix = Array<Vector>   fun spiralMatrix(n: Int): Matrix { val result = Matrix(n) { Vector(n) } var pos = 0 var count = n var value = -n var sum = -1 do { value = -value / n for (i in 0 until count) { sum += va...
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#Go
Go
package main   import ( "bytes" "encoding/binary" "fmt" )   // declarations for word size of data type word int32 const wordLen = 4 const highBit = -1 << 31   var data = []word{170, 45, 75, -90, -802, 24, 2, 66}   func main() { buf := bytes.NewBuffer(nil) ds := make([][]byte, len(data)) for i, x...
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ALGOL_68
ALGOL 68
#--- Swap function ---# PROC swap = (REF []INT array, INT first, INT second) VOID: ( INT temp := array[first]; array[first] := array[second]; array[second]:= temp );   #--- Quick sort 3 arg function ---# PROC quick = (REF [] INT array, INT first, INT last) VOID: ( INT smaller := first + 1, lar...
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
import std.stdio, std.array, std.range, std.algorithm;   void patienceSort(T)(T[] items) /*pure nothrow @safe*/ if (__traits(compiles, T.init < T.init)) { //SortedRange!(int[][], q{ a.back < b.back }) piles; T[][] piles;   foreach (x; items) { auto p = [x]; immutable i = piles.length - ...
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#360_Assembly
360 Assembly
* Insertion sort 16/06/2016 INSSORT CSECT USING INSSORT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " ...
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#J
J
ps =:(1+])^:((-.@-:/:~)@A.~)^:_ 0:
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Java
Java
import java.util.List; import java.util.ArrayList; import java.util.Arrays;   public class PermutationSort { public static void main(String[] args) { int[] a={3,2,1,8,9,4,6}; System.out.println("Unsorted: " + Arrays.toString(a)); a=pSort(a); System.out.println("Sorted: " + Arrays.toString(a)); } public sta...
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <iterator> #include <vector>   // pancake sort template (calls predicate to determine order) template <typename BidIt, typename Pred> void pancake_sort(BidIt first, BidIt last, Pred order) { if (std::distance(first, last) < 2) return; // no sort needed   for (; ...
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Scala
Scala
val n = 1 + 2
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Seed7
Seed7
audible alert BEL \a backslash (\) \\ backspace BS \b apostrophe (') \' escape ESC \e double quote (") \" formfeed FF \f newline NL (LF) \n control-A \A carriage return CR \r ... horizo...
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#SQL
SQL
' ' String literal " " Identifier [ ] Identifier ` ` Identifier ? Numbered host parameter : Named host parameter $ Named host parameter @ Named host parameter ( ) Parentheses + Add - Subtract/negative * Multiply / Divide % Modulo & Bitwise AND | Bitwise OR ~ Bitwise NOT << Lef...
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#jq
jq
def stoogesort: def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;   # for efficiency, define an auxiliary function # that takes as input [L, i, j] def ss: .[1] as $i | .[2] as $j | .[0] | if .[$j] < .[$i] then swap($i;$j) else . end | if $j - $i > 1 then (($j - $i + 1) / 3 | floor) a...
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Julia
Julia
function stoogesort!(a::Array, i::Int=1, j::Int=length(a)) if a[j] < a[i] a[[i, j]] = a[[j, i]]; end   if (j - i) > 1 t = round(Int, (j - i + 1) / 3) a = stoogesort!(a, i, j - t) a = stoogesort!(a, i + t, j) a = stoogesort!(a, i, j - t) end   return a ...
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Ol
Ol
  (define (sleep-sort lst) (for-each (lambda (timeout) (async (lambda () (sleep timeout) (print timeout)))) lst))   (sleep-sort '(5 8 2 7 9 10 5))  
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Pascal
Pascal
  program sleepsort; {$IFDEF FPC} {$MODE DELPHI} {$Optimization ON,ALL} {$ElSE} {$APPTYPE CONSOLE} {$ENDIF} uses {$IFDEF UNIX} cthreads, {$ENDIF} SysUtils;   const HiLimit = 40; type tCombineForOneThread = record cft_count : Uint64; cft_ThreadID: NativeUint; cft_ThreadHandle: NativeUint; e...
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(defun selection-sort-vector (array predicate) (do ((length (length array)) (i 0 (1+ i))) ((eql i length) array) (do ((mindex i) (min (aref array i)) (j i (1+ j))) ((eql j length) (rotatef (aref array i) (aref array mindex))) (when (funcall predicate (aref arr...
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#D
D
import std.stdio: writeln; import std.string: soundex;   void main() { assert(soundex("soundex") == "S532"); assert(soundex("example") == "E251"); assert(soundex("ciondecks") == "C532"); assert(soundex("ekzampul") == "E251"); assert(soundex("Robert") == "R163"); assert(soundex("Rupert") == "R163...
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Haskell
Haskell
import Data.List   shellSort xs = foldr (invColumnize (map (foldr insert []))) xs gaps where gaps = takeWhile (< length xs) $ iterate (succ.(3*)) 1 invColumnize f k = concat. transpose. f. transpose . takeWhile (not.null). unfoldr (Just. splitAt k)
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#Sidef
Sidef
var bar = @('▁'..'█'); loop { print 'Numbers, please, separated by space/commas: '; var numbers = read(String).trim.split(/[\s,]+/).map{.to_n}; var (min, max) = numbers.minmax; say "min: %5f; max: %5f"%(min, max); var div = ((max - min) / bar.end); say (min == max ? bar.last*numbers.len : number...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#Tcl
Tcl
package require Tcl 8.6   proc extractValues {series} { return [regexp -all -inline {\d+(?:\.\d*)?|\.\d+} $series] } proc renderValue {min max value} { set band [expr {int(8*($value-$min)/(($max-$min)*1.01))}] return [format "%c" [expr {0x2581 + $band}]] } proc sparkline {series} { set values [extractVa...
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Sidef
Sidef
var he_likes = Hash( abe => < abi eve cath ivy jan dee fay bea hope gay >, bob => < cath hope abi dee eve fay bea jan ivy gay >, col => < hope eve abi dee bea fay ivy gay cath jan >, dan => < ivy fay dee gay hope eve jan bea cath abi >, ed => < jan dee bea cath fay eve abi ivy hope gay >, ...
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Kotlin
Kotlin
// version 1.1.2   class Stack<E> { private val data = mutableListOf<E>()   val size get() = data.size   val empty get() = size == 0   fun push(element: E) = data.add(element)   fun pop(): E { if (empty) throw RuntimeException("Can't pop elements from an empty stack") return data.rem...
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Liberty_BASIC
Liberty BASIC
nomainwin   UpperLeftX = 50 UpperLeftY = 50 WindowWidth =900 WindowHeight =930   statictext #w.st, "", 10, 850, 870, 40   open "Spiral matrix" for graphics_nsb_nf as #w   #w "trapclose [quit]" #w "backcolor darkblue; color cyan; fill darkblue"   for N =2 to 50   #w.st "!font courier_new "; int( 60 /N); " bold...
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#Groovy
Groovy
def radixSort = { final radixExponent, list -> def fromBuckets = new TreeMap([0:list]) def toBuckets = new TreeMap() final radix = 2**radixExponent final mask = radix - 1 final radixDigitSize = (int)Math.ceil(64/radixExponent) final digitWidth = radixExponent (0..<radixDigitSize).each { radi...
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ALGOL_W
ALGOL W
% Quicksorts in-place the array of integers v, from lb to ub % procedure quicksort ( integer array v( * )  ; integer value lb, ub ) ; if ub > lb then begin  % more than one element, so must sort % integer left, right, pivot; left  := lb; right  := ub;  % choosin...
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Elixir
Elixir
defmodule Sort do def patience_sort(list) do piles = deal_pile(list, []) merge_pile(piles, []) end   defp deal_pile([], piles), do: piles defp deal_pile([h|t], piles) do index = Enum.find_index(piles, fn pile -> hd(pile) <= h end) new_piles = if index, do: add_element(piles, index, h, []), ...
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program insertionSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeConstant...
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#jq
jq
def permutations: if length == 0 then [] else . as $in | range(0;length) as $i | ($in|del(.[$i])|permutations) | [$in[$i]] + . end ;
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Julia
Julia
# v0.6   using Combinatorics   function permsort(x::Array) for perm in permutations(x) if issorted(perm) return perm end end end   x = randn(10) @show x permsort(x)
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Kotlin
Kotlin
// version 1.1.2   fun <T : Comparable<T>> isSorted(list: List<T>): Boolean { val size = list.size if (size < 2) return true for (i in 1 until size) { if (list[i] < list[i - 1]) return false } return true }   fun <T : Comparable<T>> permute(input: List<T>): List<List<T>> { if (input.size...
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Clojure
Clojure
  (defn pancake-sort [arr] (if (= 1 (count arr)) arr (when-let [mx (apply max arr)] (let [tk (split-with #(not= mx %) arr) tail (second tk) torev (concat (first tk) (take 1 tail)) head (reverse torev)] (cons mx (pancake-sort (concat (drop 1 head) (drop ...
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Tcl
Tcl
{...} ;# group in one word, without substituting content; nests "..." ;# group in one word, with substituting content [...] ;# evaluate content as script, then substitute with its result; nests $foo ;# substitute with content of variable foo $bar(foo) ;# substitute with content of element 'foo' of arra...
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Kotlin
Kotlin
// version 1.1.0   fun stoogeSort(a: IntArray, i: Int, j: Int) { if (a[j] < a[i]) { val temp = a[j] a[j] = a[i] a[i] = temp } if (j - i > 1) { val t = (j - i + 1) / 3 stoogeSort(a, i, j - t) stoogeSort(a, i + t, j) stoogeSort(a, i, j - t) } }   fun...
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Perl
Perl
1 while ($_ = shift and @ARGV and !fork); sleep $_; print "$_\n"; wait;
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Phix
Phix
without js -- (multitasking) integer count procedure sleeper(integer key) ? key -- (or maybe res &= key) count -= 1 end procedure --sequence s = command_line()[3..$] sequence s = split("3 1 4 1 5 9 2 6 5") if length(s)=0 then puts(1,"Nothing to sort.\n") else count = 0 for i=1 to length(s) do ...
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Crystal
Crystal
def selectionSort(array : Array) (0...array.size-1).each do |i| nextMinIndex = i (i+1...array.size).each do |j| if array[j] < array[nextMinIndex] nextMinIndex = j end end if i != nextMinIndex array.swap(i, nextMinIndex) ...
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
import std.stdio, std.algorithm, std.array, std.traits;   enum AreSortableArrayItems(T) = isMutable!T && __traits(compiles, T.init < T.init) && !isNarrowString!(T[]);   void selectionSort(T)(T[] data) if (AreSortableArrayItems!T) { foreach (immutable i...
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Delphi
Delphi
program SoundexDemo;   {$APPTYPE CONSOLE}   uses System.StrUtils;   begin Writeln(Soundex('Ashcraft')); Writeln(Soundex('Tymczak')) end.
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Haxe
Haxe
class ShellSort { @:generic public static function sort<T>(arr:Array<T>) { var h = arr.length; while (h > 0) { h >>= 1; for (i in h...arr.length) { var k = arr[i]; var j = i; while (j >= h && Reflect.compare(k, arr[j - h]) < 0) { arr[j] = arr[j - h]; ...
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string demosort(shellsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") end   procedure shellsort(X,op) #: return sorted X local i,j,inc,temp   op := sortop(op,X) # select how and what we sort   inc := *X/2 ...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#Wren
Wren
import "io" for Stdin, Stdout import "/pattern" for Pattern   var p = Pattern.new("[,+1/s|+1/s,|+1/s|,]")   var spark = Fn.new { |s0| var ss = p.splitAll(s0) var n = ss.count var vs = List.filled(n, 0) var min = 1/0 var max = -min var i = 0 for (s in ss) { var v = Num.fromString(s) ...
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#SPARK_.2F_Ada
SPARK / Ada
package Preferences is   type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon); subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last;   type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan); subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_...
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#lang5
lang5
: cr "\n" . ; : empty? dup execute length if 0 else -1 then swap drop ; : pop dup execute length 1 - extract swap drop ; : push dup execute rot append over ; : s. stack execute . ;   [] '_ set : stack '_ ; stack # local variable 1 swap push set 2 swap push set s. cr # [ 1 2 ] ...
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Lua
Lua
av, sn = math.abs, function(s) return s~=0 and s/av(s) or 0 end function sindex(y, x) -- returns the value at (x, y) in a spiral that starts at 1 and goes outwards if y == -x and y >= x then return (2*y+1)^2 end local l = math.max(av(y), av(x)) return (2*l-1)^2+4*l+2*l*sn(x+y)+sn(y^2-x^2)*(l-(av(y)==l and sn(y)*x...
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#Haskell
Haskell
import Data.Bits (Bits(testBit, bitSize)) import Data.List (partition)   lsdSort :: (Ord a, Bits a) => [a] -> [a] lsdSort = fixSort positiveLsdSort   msdSort :: (Ord a, Bits a) => [a] -> [a] msdSort = fixSort positiveMsdSort   -- Fix a sort that puts negative numbers at the end, like positiveLsdSort and positiveMsdSort...
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#APL
APL
qsort ← {1≥⍴⍵:⍵ ⋄ e←⍵[?⍴⍵] ⋄ (∇(⍵<e)/⍵) , ((⍵=e)/⍵) , (∇(⍵>e)/⍵)} qsort 31 4 1 5 9 2 6 5 3 5 8 1 2 3 4 5 5 5 6 8 9 31
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Fortran
Fortran
Warning: trampoline generated for nested function "less" [-Wtrampolines]
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ACL2
ACL2
(defun insert (x xs) (cond ((endp xs) (list x)) ((< x (first xs)) (cons x xs)) (t (cons (first xs) (insert x (rest xs))))))   (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs)))))
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Lua
Lua
-- Return an iterator to produce every permutation of list function permute (list) local function perm (list, n) if n == 0 then coroutine.yield(list) end for i = 1, n do list[i], list[n] = list[n], list[i] perm(list, n - 1) list[i], list[n] = list[n], list[i] end end return coroutine...
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(defun pancake-sort (seq) "A destructive version of Pancake Sort that works with either lists or arrays of numbers." (defun flip (lst index) (setf (subseq lst 0 index) (reverse (subseq lst 0 index)))) (loop with lst = (coerce seq 'list) for i from (length lst) downto 2 for index = (position (apply #'max (su...
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
import std.stdio, std.algorithm;   void pancakeSort(bool tutor=false, T)(T[] data) { foreach_reverse (immutable i; 2 .. data.length + 1) { immutable maxIndex = i - data[0 .. i].minPos!q{a > b}.length; if (maxIndex + 1 != i) { if (maxIndex != 0) { static if (tutor) ...
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Lua
Lua
  local Y = function (f) return (function(x) return x(x) end)(function(x) return f(function(...) return x(x)(...) end) end) end   function stoogesort(L, pred)   pred = pred or function(a,b) return a < b end   Y(function(recurse) return function(i,j) if pred(L[j], L[i]) then L[j],L[i] = L[i],L[j]...
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#PicoLisp
PicoLisp
(de sleepSort (Lst) (make (for (I . N) Lst (task (- I) (* N 100) N N I I (link N) (pop 'Lst) (task (- I)) ) ) (wait NIL (not Lst)) ) )
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#Pike
Pike
  #!/usr/bin/env pike   int main(int argc, array(string) argv) { foreach(argv[1..], string value) { int v = (int)value; if(v<0) continue; call_out(print, v, value); } return -1; }   void print(string value) { ...
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Dart
Dart
  void main() { List<int> a = selectionSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]); print('$a'); }   selectionSort(List<int> array){ for(int currentPlace = 0;currentPlace<array.length-1;currentPlace++){ int smallest = 4294967296; //maxInt int smallestAt = currentPlace+1; for(int check = currentPl...
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Delphi
Delphi
program TestSelectionSort;   {$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...
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Elixir
Elixir
defmodule Soundex do def soundex([]), do: [] def soundex(str) do [head|tail] = String.upcase(str) |> to_char_list [head | isoundex(tail, [], todigit(head))] end   defp isoundex([], acc, _) do case length(acc) do n when n == 3 -> Enum.reverse(acc) n when n < 3 -> isoundex([], [?0 | acc],...
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Io
Io
List do( shellSortInPlace := method( gap := (size / 2) round while(gap > 0, for(i, gap, size - 1, key := at(i) j := i   while(j >= gap and at(j - gap) > key, atPut(j, at(j - gap)) j = j - gap ...
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#IS-BASIC
IS-BASIC
100 PROGRAM "ShellSrt.bas" 110 RANDOMIZE 120 LET N=20 ! Number of elements 130 NUMERIC ARRAY(1 TO N) 140 CALL INIT(ARRAY) 150 CALL WRITE(ARRAY) 160 CALL SHELLSORT(ARRAY) 170 CALL WRITE(ARRAY) 180 DEF INIT(REF A) 190 FOR I=LBOUND(A) TO UBOUND(A) 200 LET A(I)=RND(N)+1 210 NEXT 220 END DEF 230 DEF WRITE(REF A) 24...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#zkl
zkl
var sparks=[0x2581..0x2588].apply("toString",-8); // int.toString(-8)-->UTF-8 var sl=(sparks.len()-1);   fcn sparkLine(xs){ min:=(0.0).min(xs); max:=(0.0).max(xs); // min/max are float reguardless of xs range:=max-min; // float println("Range [",min,"-",max,"]", xs); xs.pump(String,'wrap(x){ sparks[(x - m...
http://rosettacode.org/wiki/Sparkline_in_unicode
Sparkline in unicode
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. Task Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a s...
#Zoea
Zoea
  program: sparkline input: '1 2, 3 4.5 5 6,7 8' derive: [1,2,3,4.5,5,6,7,8] derive: [1,2,3,4,5,6,7,8] output: '▁▂▃▄▅▆▇█'  
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Swift
Swift
class Person { let name:String var candidateIndex = 0 var fiance:Person? var candidates = [Person]()   init(name:String) { self.name = name }   func rank(p:Person) -> Int { for (i, candidate) in enumerate(self.candidates) { if candidate === p { ret...
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Lasso
Lasso
local(a) = array   #a->push('a') #a->push('b') #a->push('c')   #a->pop // c #a->pop // b #a->pop // a #a->pop // null
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Maple
Maple
  with(ArrayTools):   spiralArray := proc(size::integer) local M, sideLength, count, i, j: M := Matrix(size): count := 0: sideLength := size: for i from 1 to ceil(sideLength / 2) do for j from 1 to sideLength do M[i,i + j - 1] := count++: end: for j from 1 to sideLength - 1 do M[i + j, sideLength + i -...
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every writes((!rSort(A)||" ")|"\n") end   procedure rSort(A) every (min := A[1]) >:= !A every (mlen := *(A[1]-min)) <:= (!A - min) every i := !*mlen do { every put(b := [], |[]\12) every a := !A do put(b[(a-min)[-i]+2|1], a) every put(A := [],!!b) } ...
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AppleScript
AppleScript
-- quickSort :: (Ord a) => [a] -> [a] on quickSort(xs) if length of xs > 1 then set {h, t} to uncons(xs)   -- lessOrEqual :: a -> Bool script lessOrEqual on |λ|(x) x ≤ h end |λ| end script   set {less, more} to partition(lessOrEqual, t)...
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Go
Go
package main   import ( "fmt" "container/heap" "sort" )   type IntPile []int func (self IntPile) Top() int { return self[len(self)-1] } func (self *IntPile) Pop() int { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x }   type IntPilesHeap []IntPile func (self IntPilesHeap) Len() int...