code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
null | 219Special characters | 8haskell | yis66 |
void StoogeSort(int a[], int i, int j)
{
int t;
if (a[j] < a[i]) SWAP(a[i], a[j]);
if (j - i > 1)
{
t = (j - i + 1) / 3;
StoogeSort(a, i, j - t);
StoogeSort(a, i + t, j);
StoogeSort(a, i, j - t);
}
}
int main(int argc, char *argv[])
{
int nums[] = {1, 4, 5, 3, -6, 3, 7, ... | 221Sorting algorithms/Stooge sort | 5c | 6ow32 |
(ns sleepsort.core
(require [clojure.core.async:as async:refer [chan go <! <!! >! timeout]]))
(defn sleep-sort [l]
(let [c (chan (count l))]
(doseq [i l]
(go (<! (timeout (* 1000 i)))
(>! c i)))
(<!! (async/into [] (async/take (count l) c))))) | 220Sorting algorithms/Sleep sort | 6clojure | 9d0ma |
import Data.List.Split (splitOneOf)
import Data.Char (chr)
toSparkLine :: [Double] -> String
toSparkLine xs = map cl xs
where
top = maximum xs
bot = minimum xs
range = top - bot
cl x = chr $ 0x2581 + floor (min 7 ((x - bot) / range * 8))
makeSparkLine :: String -> (String, Stats)
makeSparkLine xs =... | 217Sparkline in unicode | 8haskell | p4ubt |
data class Person(val name: String) {
val preferences = mutableListOf<Person>()
var matchedTo: Person? = null
fun trySwap(p: Person) {
if (prefers(p)) {
matchedTo?.matchedTo = null
matchedTo = p
p.matchedTo = this
}
}
fun prefers(p: Person) = whe... | 214Stable marriage problem | 11kotlin | p4gb6 |
public extension String {
func splitOnChanges() -> [String] {
guard!isEmpty else {
return []
}
var res = [String]()
var workingChar = first!
var workingStr = "\(workingChar)"
for char in dropFirst() {
if char!= workingChar {
res.append(workingStr)
workingStr = "\(... | 210Split a character string based on change of character | 17swift | tsnfl |
public class Sparkline
{
String bars="";
public static void main(String[] args)
{
Sparkline now=new Sparkline();
float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
now.display1D(arr);
System.out.println(now.getSparkline(arr));
float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};
now.di... | 217Sparkline in unicode | 9java | rcmg0 |
local Person = {}
Person.__index = Person
function Person.new(inName)
local o = {
name = inName,
prefs = nil,
fiance = nil,
_candidateIndex = 1,
}
return setmetatable(o, Person)
end
function Person:indexOf(other)
for i, p in pairs(self.pref... | 214Stable marriage problem | 1lua | 1grpo |
(() => {
'use strict';
const main = () => { | 217Sparkline in unicode | 10javascript | b5vki |
use English;
$. $INPUT_LINE_NUMBER
$, $OUTPUT_FIELD_SEPARATOR
$; $SUBSCRIPT_SEPARATOR
$_ $ARG
$" $LIST_SEPARATOR
$+ $LAST_PAREN_MATCH
$0 $PROGRAM_NAME
$! $ERRNO
$@ $EVAL_... | 215Special variables | 2perl | 4mm5d |
& | ^ ~ | 219Special characters | 9java | dx1n9 |
^[a-zA-Z_][a-zA-Z_0-9]*$ | 219Special characters | 10javascript | 6oq38 |
(defn swap [v x y]
(assoc! v y (v x) x (v y)))
(defn stooge-sort
([v] (persistent! (stooge-sort (transient v) 0 (dec (count v)))))
([v i j]
(if (> (v i) (v j)) (swap v i j) v)
(if (> (- j i) 1)
(let [t (int (Math/floor (/ (inc (- j i)) 3)))]
(stooge-sort v i (- j t))
(stooge-sort ... | 221Sorting algorithms/Stooge sort | 6clojure | lt8cb |
void main() async {
Future<void> sleepsort(Iterable<int> input) => Future.wait(input
.map((i) => Future.delayed(Duration(milliseconds: i), () => print(i))));
await sleepsort([3, 10, 2, 120, 122, 121, 54]);
} | 220Sorting algorithms/Sleep sort | 18dart | oah8s |
internal const val bars = ""
internal const val n = bars.length - 1
fun <T: Number> Iterable<T>.toSparkline(): String {
var min = Double.MAX_VALUE
var max = Double.MIN_VALUE
val doubles = map { it.toDouble() }
doubles.forEach { i -> when { i < min -> min = i; i > max -> max = i } }
val range = max ... | 217Sparkline in unicode | 11kotlin | v3t21 |
use strict;
use warnings;
use feature 'say';
sub merge {
my ($x, $y) = @_;
my @out;
while (@$x and @$y) {
my $t = $x->[-1] <=> $y->[-1];
if ($t == 1) { unshift @out, pop @$x }
elsif ($t == -1) { unshift @out, pop @$y }
else { splice @out, 0, 0, pop(@$x), pop(... | 216Sorting algorithms/Strand sort | 2perl | wj7e6 |
typedef int(*cmp_func)(const void*, const void*);
void perm_sort(void *a, int n, size_t msize, cmp_func _cmp)
{
char *p, *q, *tmp = malloc(msize);
memcpy(tmp, a, msize);\
memcpy(a, b, msize);\
memcpy(b, tmp, msize); }
while (1) {
for (p = A(n - 1); (void*)p > a; p = q)
if (_cmp(q = p - msize, p) > 0)... | 222Sorting algorithms/Permutation sort | 5c | lt0cy |
# defined local ie. #mylocal will fail if not defined
$ defined variable ie. $myvar will fail if not defined
= assignment
:= assign as return assigned value
? ternary conditional true? this
| ternary else false? this | that
|| or
&& and
! negative operator
{ open capture
} close capture
=> specify givenblock / capture ... | 219Special characters | 11kotlin | 0pjsf |
void shell_sort (int *a, int n) {
int h, i, j, t;
for (h = n; h /= 2;) {
for (i = h; i < n; i++) {
t = a[i];
for (j = i; j >= h && t < a[j - h]; j -= h) {
a[j] = a[j - h];
}
a[j] = t;
}
}
}
int main (int ac, char **av) {
in... | 223Sorting algorithms/Shell sort | 5c | 7ltrg |
var intStack []int | 212Stack | 0go | 4ml52 |
names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) ) | 215Special variables | 3python | g994h |
$lst = new SplDoublyLinkedList();
foreach (array(1,20,64,72,48,75,96,55,42,74) as $v)
$lst->push($v);
foreach (strandSort($lst) as $v)
echo ;
function strandSort(SplDoublyLinkedList $lst) {
$result = new SplDoublyLinkedList();
while (!$lst->isEmpty()) {
$sorted = new SplDoublyLinkedList();
... | 216Sorting algorithms/Strand sort | 12php | ltfcj |
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay h... | 214Stable marriage problem | 2perl | yin6u |
def stack = []
assert stack.empty
stack.push(55)
stack.push(21)
stack.push('kittens')
assert stack.last() == 'kittens'
assert stack.size() == 3
assert ! stack.empty
println stack
assert stack.pop() == "kittens"
assert stack.size() == 2
println stack
stack.push(-20)
println stack
stack.push( stack.pop() * stack.p... | 212Stack | 7groovy | lt6c1 |
Markup:
() Sequence
{} List
" String
\ Escape for following character
(* *) Comment block
base^^number`s
` Context
[[]] Indexed reference
Within expression:
\ At end of line: Continue on next line, skipping white space | 219Special characters | 1lua | 81h0e |
type Stack a = [a]
create :: Stack a
create = []
push :: a -> Stack a -> Stack a
push = (:)
pop :: Stack a -> (a, Stack a)
pop [] = error "Stack empty"
pop (x:xs) = (x,xs)
empty :: Stack a -> Bool
empty = null
peek :: Stack a -> a
peek [] = error "Stack empty"
peek (x:_) = x | 212Stack | 8haskell | qk1x9 |
package main
import (
"fmt"
"strconv"
)
var n = 5
func main() {
if n < 1 {
return
}
top, left, bottom, right := 0, 0, n-1, n-1
sz := n * n
a := make([]int, sz)
i := 0
for left < right { | 218Spiral matrix | 0go | wjgeg |
(use '[clojure.contrib.combinatorics :only (permutations)])
(defn permutation-sort [s]
(first (filter (partial apply <=) (permutations s))))
(permutation-sort [2 3 5 3 5]) | 222Sorting algorithms/Permutation sort | 6clojure | 4md5o |
static char code[128] = { 0 };
void add_code(const char *s, int c)
{
while (*s) {
code[(int)*s] = code[0x20 ^ (int)*s] = c;
s++;
}
}
void init()
{
static const char *cls[] =
{ , , , , , , , , 0};
int i;
for (i = 0; cls[i]; i++)
add_code(cls[i], i - 1);
}
const char* soundex(const char *s)
{
static char... | 224Soundex | 5c | fqhd3 |
enum Direction {
East([0,1]), South([1,0]), West([0,-1]), North([-1,0]);
private static _n
private final stepDelta
private bound
private Direction(delta) {
stepDelta = delta
}
public static setN(int n) {
Direction._n = n
North.bound = 0
South.bound = n-1
... | 218Spiral matrix | 7groovy | b52ky |
import scala._
import scala.{ Predef => _, _ }
def f[M[_]]
def f(m: M[_])
_ + _
m _
m(_)
_ => 5
case _ =>
val (a, _) = (1, 2)
for (_ <- 1 to 10)
f(xs: _*)
case Seq(xs @ _*)
var i: Int = _
def abc_<>!
t._2 ... | 215Special variables | 14ruby | 7llri |
import scala._ | 215Special variables | 16scala | b55k6 |
package main
import (
"fmt"
"log"
"os"
"strconv"
"time"
)
func main() {
out := make(chan uint64)
for _, a := range os.Args[1:] {
i, err := strconv.ParseUint(a, 10, 64)
if err != nil {
log.Fatal(err)
}
go func(n uint64) {
time.Sleep(time.Duration(n) * time.Millisecond)
out <- n
}(i)
}
for _... | 220Sorting algorithms/Sleep sort | 0go | ku9hz |
@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1')
import groovyx.gpars.GParsPool
GParsPool.withPool args.size(), {
args.eachParallel {
sleep(it.toInteger() * 10)
println it
}
} | 220Sorting algorithms/Sleep sort | 7groovy | g9z46 |
binmode(STDOUT, ":utf8");
our @sparks=map {chr} 0x2581 .. 0x2588;
sub sparkline(@) {
my @n=map {0+$_} grep {length} @_ or return "";
my($min,$max)=($n[0])x2;
if (@n>1) {
for (@n[1..$
if ($_<$min) { $min=$_ }
elsif ($_>$max) { $max=$_ }
}
}
my $sparkline="";... | 217Sparkline in unicode | 2perl | 0pks4 |
def merge_list(a, b):
out = []
while len(a) and len(b):
if a[0] < b[0]:
out.append(a.pop(0))
else:
out.append(b.pop(0))
out += a
out += b
return out
def strand(a):
i, s = 0, [a.pop(0)]
while i < len(a):
if a[i] > s[-1]:
s.append(a.pop(i))
else:
i += 1
return s
def strand_sort(a):
out = st... | 216Sorting algorithms/Strand sort | 3python | xhjwr |
import Data.List
import Control.Monad
grade xs = map snd. sort $ zip xs [0..]
values n = cycle [1,n,-1,-n]
counts n = (n:).concatMap (ap (:) return) $ [n-1,n-2..1]
reshape n = unfoldr (\xs -> if null xs then Nothing else Just (splitAt n xs))
spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts ... | 218Spiral matrix | 8haskell | 6os3k |
import System.Environment
import Control.Concurrent
import Control.Monad
sleepSort :: [Int] -> IO ()
sleepSort values = do
chan <- newChan
forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time))
forM_ values (\_ -> readChan chan >>= print)
main :: IO ()
main = getArg... | 220Sorting algorithms/Sleep sort | 8haskell | nwbie |
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
unsigned *ll = from, *rr = to - 1;
for (;;) {
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*r... | 225Sorting algorithms/Radix sort | 5c | 0pust |
import java.util.concurrent.CountDownLatch;
public class SleepSort {
public static void sleepSortAndPrint(int[] nums) {
final CountDownLatch doneSignal = new CountDownLatch(nums.length);
for (final int num: nums) {
new Thread(new Runnable() {
public void run() {
doneSignal.countDown();
try {
... | 220Sorting algorithms/Sleep sort | 9java | qkgxa |
void main() {
List<int> a = shellSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]);
print('$a');
}
shellSort(List<int> array) {
int n = array.length; | 223Sorting algorithms/Shell sort | 18dart | v382j |
bar = ''
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __name__ == '... | 217Sparkline in unicode | 3python | 81b0o |
import copy
guyprefers = {
'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... | 214Stable marriage problem | 3python | mndyh |
package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
stoogesort(a)
fmt.Println("after: ", a)
fmt.Println("nyuk nyuk nyuk")
}
func stoogesort(a []int) {
last := len(a) - 1
if a[last] < a[0] {
a[0], a[last] = a[last], a[0]
... | 221Sorting algorithms/Stooge sort | 0go | p4cbg |
Array.prototype.timeoutSort = function (f) {
this.forEach(function (n) {
setTimeout(function () { f(n) }, 5 * n)
});
} | 220Sorting algorithms/Sleep sort | 10javascript | iekol |
bars <- intToUtf8(seq(0x2581, 0x2588), multiple = T)
n_chars <- length(bars)
sparkline <- function(numbers) {
mn <- min(numbers)
mx <- max(numbers)
interval <- mx - mn
bins <- sapply(
numbers,
function(i)
bars[[1 + min(n_chars - 1, floor((i - mn) / interval * n_chars))]]
)
sparkline <- pa... | 217Sparkline in unicode | 13r | xh7w2 |
class Array
def strandsort
a = dup
result = []
until a.empty?
v = a.first
sublist, a = a.partition{|val| v=val if v<=val}
result.each_index do |idx|
break if sublist.empty?
result.insert(idx, sublist.shift) if sublist.first < result[idx]
end
result += subl... | 216Sorting algorithms/Strand sort | 14ruby | sbkqw |
Delimiters
Operators , =:= ==!= < <= > >= @= @== @!= @< @<= @> @>= + - * / += -= *= /= @+= @-= @*= @/= .. & &=?;: |
Braces ()[]{}
BlockComment /* */ --/* --*/
LineComment --
TokenStart abcedfghijklmnopqrstuvwxyz
TokenStart ABCDEFGHIJKLMNOPQRSTUVWXYZ_
TokenChar 0123456789
Escapes \rnt\'"eE | 219Special characters | 2perl | 5ytu2 |
import Data.List
import Control.Arrow
import Control.Monad
insertAt e k = uncurry(++).second ((e:).drop 1). splitAt k
swapElems :: [a] -> Int -> Int -> [a]
swapElems xs i j = insertAt (xs!!j) i $ insertAt (xs!!i) j xs
stoogeSort [] = []
stoogeSort [x] = [x]
stoogeSort xs = doss 0 (length xs - 1) xs
doss :: (Ord a) ... | 221Sorting algorithms/Stooge sort | 8haskell | fqpd1 |
null | 220Sorting algorithms/Sleep sort | 11kotlin | 1g2pd |
void selection_sort (int *a, int n) {
int i, j, m, t;
for (i = 0; i < n; i++) {
for (j = i, m = i; j < n; j++) {
if (a[j] < a[m]) {
m = j;
}
}
t = a[i];
a[i] = a[m];
a[m] = t;
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, ... | 226Sorting algorithms/Selection sort | 5c | dxrnv |
(defn 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
nil))
(defn soundex [s]
(let [[f & s] (.toUpperCase s)]
(-> (map get-code s)
distinct
(concat , "0000")
(->> (cons f ,)
(remove nil? ,)
(take 4 ,)
(apply s... | 224Soundex | 6clojure | yia6b |
import java.util.Stack;
public class StackTest {
public static void main( final String[] args ) {
final Stack<String> stack = new Stack<String>();
System.out.println( "New stack empty? " + stack.empty() );
stack.push( "There can be only one" );
System.out.println( "Pushed stack em... | 212Stack | 9java | p47b3 |
public class Blah {
public static void main(String[] args) {
print2dArray(getSpiralArray(5));
}
public static int[][] getSpiralArray(int dimension) {
int[][] spiralArray = new int[dimension][dimension];
int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);
int j;
int sideLen = dim... | 218Spiral matrix | 9java | nw1ih |
function sleeprint(n)
local t0 = os.time()
while os.time() - t0 <= n do
coroutine.yield(false)
end
print(n)
return true
end
coroutines = {}
for i=1, #arg do
wrapped = coroutine.wrap(sleeprint)
table.insert(coroutines, wrapped)
wrapped(tonumber(arg[i]))
end
done = false
while not done do
done = t... | 220Sorting algorithms/Sleep sort | 1lua | arv1v |
var stack = [];
stack.push(1)
stack.push(2,3);
print(stack.pop()); | 212Stack | 10javascript | xhpw9 |
spiralArray = function (edge) {
var arr = Array(edge),
x = 0, y = edge,
total = edge * edge--,
dx = 1, dy = 0,
i = 0, j = 0;
while (y) arr[--y] = [];
while (i < total) {
arr[y][x] = i++;
x += dx; y += dy;
if (++j == edge) {
if (dy < 0) {x++... | 218Spiral matrix | 10javascript | 38qz0 |
int* patienceSort(int* arr,int size){
int decks[size][size],i,j,min,pickedRow;
int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));
for(i=0;i<size;i++){
for(j=0;j<size;j++){
if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){
decks[j][count[j]] = arr[i];
... | 227Sorting algorithms/Patience sort | 5c | e7yav |
package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66} | 222Sorting algorithms/Permutation sort | 0go | xhuwf |
bar = (''..'').to_a
loop {print 'Numbers please separated by space/commas: '
numbers = gets.split(/[\s,]+/).map(&:to_f)
min, max = numbers.minmax
puts % [min, max]
div = (max - min) / (bar.size - 1)
puts min == max? bar.last*numbers.size: numbers.map{|num| bar[((num - min) / div).to_i]}.join
} | 217Sparkline in unicode | 14ruby | ie1oh |
const BARS: &'static str = "";
fn print_sparkline(s: &str){
let v = BARS.chars().collect::<Vec<char>>();
let line: String = s.replace(",", " ").split(" ")
.filter(|x|!x.is_empty())
.map(|x| v[x.parse::<f64>().unwrap().ceil() as usize - 1])
... | 217Sparkline in unicode | 15rust | nwai4 |
class Person
def initialize(name)
@name = name
@fiance = nil
@preferences = []
@proposals = []
end
attr_reader :name, :proposals
attr_accessor :fiance, :preferences
def to_s
@name
end
def free
@fiance = nil
end
def single?
@fiance == nil
end
def engage(person)
s... | 214Stable marriage problem | 14ruby | cft9k |
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j }: 1 }
def makePermutation;
makePermutation = { list, i ->
def n = list.size()
if (n < 2) return list
def fact = factorial(n-1)
assert i < fact*n
def index = i.intdiv(fact)
[list[index]] + makePermutation(list[0..<index] + list[(inde... | 222Sorting algorithms/Permutation sort | 7groovy | p49bo |
int pancake_sort(int *list, unsigned int length)
{
if(length<2)
return 0;
int i,a,max_num_pos,moves;
moves=0;
for(i=length;i>1;i--)
{
max_num_pos=0;
for(a=0;a<i;a++)
{
if(list[a]>list[max_num_pos])
max_num_pos=a;
}
... | 228Sorting algorithms/Pancake sort | 5c | xhmwu |
$ Item
@ Positional
% Associative
& Callable | 219Special characters | 3python | 4mz5k |
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);
... | 221Sorting algorithms/Stooge sort | 9java | 0prse |
(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]
(... | 226Sorting algorithms/Selection sort | 6clojure | 6ob3q |
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 ... | 217Sparkline in unicode | 16scala | tsxfb |
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)
... | 214Stable marriage problem | 16scala | u6yv8 |
(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))
(let [stack (first sequence)
top (peek s... | 227Sorting algorithms/Patience sort | 6clojure | 0p2sj |
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' <- inser... | 222Sorting algorithms/Permutation sort | 8haskell | yiw66 |
val n = 1 + 2 | 219Special characters | 14ruby | rc6gs |
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((j -... | 221Sorting algorithms/Stooge sort | 10javascript | dxbnu |
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 {
... | 223Sorting algorithms/Shell sort | 0go | dxhne |
null | 218Spiral matrix | 11kotlin | sbjq7 |
package main
import (
"bytes"
"encoding/binary"
"fmt"
) | 225Sorting algorithms/Radix sort | 0go | u60vt |
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 stat... | 222Sorting algorithms/Permutation sort | 9java | dxkn9 |
val n = 1 + 2 | 219Special characters | 16scala | kuchk |
' ' 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
<< Left s... | 219Special characters | 19sql | 1gvpg |
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) | 223Sorting algorithms/Shell sort | 8haskell | 5yiug |
null | 212Stack | 11kotlin | 7lur4 |
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... | 225Sorting algorithms/Radix sort | 7groovy | 9dem4 |
null | 222Sorting algorithms/Permutation sort | 11kotlin | 0pgsf |
(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 1 ... | 228Sorting algorithms/Pancake sort | 6clojure | oav8j |
null | 221Sorting algorithms/Stooge sort | 11kotlin | e7va4 |
1 while ($_ = shift and @ARGV and !fork);
sleep $_;
print "$_\n";
wait; | 220Sorting algorithms/Sleep sort | 2perl | mnsyz |
av, sn = math.abs, function(s) return s~=0 and s/av(s) or 0 end
function sindex(y, x) | 218Spiral matrix | 1lua | 0phsd |
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
fixSort sorter list = uncurry (flip (++)) (break (< 0) (sorter list))
positiveLsdSort :: (Bits... | 225Sorting algorithms/Radix sort | 8haskell | wjced |
null | 222Sorting algorithms/Permutation sort | 1lua | 81r0e |
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]
... | 221Sorting algorithms/Stooge sort | 1lua | wjuea |
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; | 226Sorting algorithms/Selection sort | 18dart | sb2q6 |
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 {
retur... | 214Stable marriage problem | 17swift | 9dfmj |
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 { ... | 227Sorting algorithms/Patience sort | 0go | 9d1mt |
public static void shell(int[] a) {
int increment = a.length / 2;
while (increment > 0) {
for (int i = increment; i < a.length; i++) {
int j = i;
int temp = a[i];
while (j >= increment && a[j - increment] > temp) {
a[j] = a[j - increment];
j = j - increment;
}
a[j] = temp;
}
if (increment... | 223Sorting algorithms/Shell sort | 9java | 9dxmu |
public static int[] sort(int[] old) { | 225Sorting algorithms/Radix sort | 9java | kuzhm |
import Control.Monad.ST
import Control.Monad
import Data.Array.ST
import Data.List
import qualified Data.Set as S
newtype Pile a = Pile [a]
instance Eq a => Eq (Pile a) where
Pile (x:_) == Pile (y:_) = x == y
instance Ord a => Ord (Pile a) where
Pile (x:_) `compare` Pile (y:_) = x `compare` y
patienceSort :: Or... | 227Sorting algorithms/Patience sort | 8haskell | b5tk2 |
from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v: mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__ma... | 220Sorting algorithms/Sleep sort | 3python | 9d0mf |
function shellSort (a) {
for (var h = a.length; h > 0; h = parseInt(h / 2)) {
for (var i = h; i < a.length; i++) {
var k = a[i];
for (var j = i; j >= h && k < a[j - h]; j -= h)
a[j] = a[j - h];
a[j] = k;
}
}
return a;
}
var a = [];
var n =... | 223Sorting algorithms/Shell sort | 10javascript | u6ovb |
null | 225Sorting algorithms/Radix sort | 11kotlin | g9i4d |
require 'thread'
nums = ARGV.collect(&:to_i)
sorted = []
mutex = Mutex.new
threads = nums.collect do |n|
Thread.new do
sleep 0.01 * n
mutex.synchronize {sorted << n}
end
end
threads.each {|t| t.join}
p sorted | 220Sorting algorithms/Sleep sort | 14ruby | ltocl |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.