code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use std::thread;
fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
let threads: Vec<_> = nums.map(|n|
thread::spawn(move || {
thread::sleep_ms(n);
println!("{}", n); })).collect();
for t in threads { t.join(); }
}
fn main() {
sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap()));
} | 220Sorting algorithms/Sleep sort
| 15rust
| 2zilt |
object SleepSort {
def main(args: Array[String]): Unit = {
val nums = args.map(_.toInt)
sort(nums)
Thread.sleep(nums.max * 21) | 220Sorting algorithms/Sleep sort
| 16scala
| 5yfut |
null | 223Sorting algorithms/Shell sort
| 11kotlin
| z0pts |
import java.util.*;
public class PatienceSort {
public static <E extends Comparable<? super E>> void sort (E[] n) {
List<Pile<E>> piles = new ArrayList<Pile<E>>(); | 227Sorting algorithms/Patience sort
| 9java
| g984m |
sub psort {
my ($x, $d) = @_;
unless ($d //= $
$x->[$_] < $x->[$_ - 1] and return for 1 .. $
return 1
}
for (0 .. $d) {
unshift @$x, splice @$x, $d, 1;
next if $x->[$d] < $x->[$d - 1];
return 1 if psort($x, $d - 1);
}
}
my @a = map+(int rand 100), 0 .. 10;
print "Before:\t@a\n";
psort(\@a);
print "After:\t@a\n" | 222Sorting algorithms/Permutation sort
| 2perl
| 5ynu2 |
const patienceSort = (nums) => {
const piles = []
for (let i = 0; i < nums.length; i++) {
const num = nums[i]
const destinationPileIndex = piles.findIndex(
(pile) => num >= pile[pile.length - 1]
)
if (destinationPileIndex === -1) {
piles.push([num])
} else {
piles[destinationPileIndex].push(num)
}
}
for (let i = 0; i < nums.length; i++) {
let destinationPileIndex = 0
for (let p = 1; p < piles.length; p++) {
const pile = piles[p]
if (pile[0] < piles[destinationPileIndex][0]) {
destinationPileIndex = p
}
}
const distPile = piles[destinationPileIndex]
nums[i] = distPile.shift()
if (distPile.length === 0) {
piles.splice(destinationPileIndex, 1)
}
}
return nums
}
console.log(patienceSort([10,6,-30,9,18,1,-20])); | 227Sorting algorithms/Patience sort
| 10javascript
| kufhq |
function inOrder($arr){
for($i=0;$i<count($arr);$i++){
if(isset($arr[$i+1])){
if($arr[$i] > $arr[$i+1]){
return false;
}
}
}
return true;
}
function permute($items, $perms = array( )) {
if (empty($items)) {
if(inOrder($perms)){
return $perms;
}
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$res = permute($newitems, $newperms);
if($res){
return $res;
}
}
}
}
$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);
$arr = permute($arr);
echo implode(',',$arr); | 222Sorting algorithms/Permutation sort
| 12php
| oa785 |
import Foundation
for i in [5, 2, 4, 6, 1, 7, 20, 14] {
let time = dispatch_time(DISPATCH_TIME_NOW,
Int64(i * Int(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
print(i)
}
}
CFRunLoopRun() | 220Sorting algorithms/Sleep sort
| 17swift
| cf89t |
function shellsort( a )
local inc = math.ceil( #a / 2 )
while inc > 0 do
for i = inc, #a do
local tmp = a[i]
local j = i
while j > inc and a[j-inc] > tmp do
a[j] = a[j-inc]
j = j - inc
end
a[j] = tmp
end
inc = math.floor( 0.5 + inc / 2.2 )
end
return a
end
a = { -12, 3, 0, 4, 7, 4, 8, -5, 9 }
a = shellsort( a )
for _, i in pairs(a) do
print(i)
end | 223Sorting algorithms/Shell sort
| 1lua
| 381zo |
stack = {}
table.insert(stack,3)
print(table.remove(stack)) | 212Stack
| 1lua
| j2571 |
use warnings;
use strict;
sub radix {
my @tab = ([@_]);
my $max_length = 0;
length > $max_length and $max_length = length for @_;
$_ = sprintf "%0${max_length}d", $_ for @{ $tab[0] };
for my $pos (reverse -$max_length .. -1) {
my @newtab;
for my $bucket (@tab) {
for my $n (@$bucket) {
my $char = substr $n, $pos, 1;
$char = -1 if '-' eq $char;
$char++;
push @{ $newtab[$char] }, $n;
}
}
@tab = @newtab;
}
my @return;
my $negative = shift @tab;
push @return, reverse @$negative;
for my $bucket (@tab) {
push @return, @{ $bucket // [] };
}
$_ = 0 + $_ for @return;
return @return;
} | 225Sorting algorithms/Radix sort
| 2perl
| nwriw |
package main
import "fmt"
func main() {
list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
list.sort()
fmt.Println("sorted! ", list)
}
type pancake []int
func (a pancake) sort() {
for uns := len(a) - 1; uns > 0; uns-- { | 228Sorting algorithms/Pancake sort
| 0go
| ltacw |
package main
import (
"errors"
"fmt"
"unicode"
)
var code = []byte("01230127022455012623017202")
func soundex(s string) (string, error) {
var sx [4]byte
var sxi int
var cx, lastCode byte
for i, c := range s {
switch {
case !unicode.IsLetter(c):
if c < ' ' || c == 127 {
return "", errors.New("ASCII control characters disallowed")
}
if i == 0 {
return "", errors.New("initial character must be a letter")
}
lastCode = '0'
continue
case c >= 'A' && c <= 'Z':
cx = byte(c - 'A')
case c >= 'a' && c <= 'z':
cx = byte(c - 'a')
default:
return "", errors.New("non-ASCII letters unsupported")
} | 224Soundex
| 0go
| j2t7d |
def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
def flip = { list, n -> (0..<((n+1)/2)).each { makeSwap(list, it, n-it) } }
def pancakeSort = { list ->
def n = list.size()
(1..<n).reverse().each { i ->
def max = list[0..i].max()
def flipPoint = (i..0).find{ list[it] == max }
if (flipPoint != i) {
flip(list, flipPoint)
flip(list, i)
}
}
list
} | 228Sorting algorithms/Pancake sort
| 7groovy
| 6oh3o |
def soundex(s) {
def code = ""
def lookup = [
B: 1, F: 1, P: 1, V: 1,
C: 2, G: 2, J: 2, K: 2, Q: 2, S: 2, X: 2, Z: 2,
D: 3, T: 3,
L: 4,
M: 5, N: 5,
R: 6
]
s[1..-1].toUpperCase().inject(7) { lastCode, letter ->
def letterCode = lookup[letter]
if(letterCode && letterCode != lastCode) {
code += letterCode
}
}
return "${s[0]}${code}0000"[0..3]
}
println(soundex("Soundex"))
println(soundex("Sownteks"))
println(soundex("Example"))
println(soundex("Ekzampul")) | 224Soundex
| 7groovy
| 5youv |
null | 227Sorting algorithms/Patience sort
| 11kotlin
| 2zwli |
from itertools import permutations
in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next() | 222Sorting algorithms/Permutation sort
| 3python
| 4md5k |
import Data.List
import Control.Arrow
import Control.Monad
import Data.Maybe
dblflipIt :: (Ord a) => [a] -> [a]
dblflipIt = uncurry ((reverse.).(++)). first reverse
. ap (flip splitAt) (succ. fromJust. (elemIndex =<< maximum))
dopancakeSort :: (Ord a) => [a] -> [a]
dopancakeSort xs = dopcs (xs,[]) where
dopcs ([],rs) = rs
dopcs ([x],rs) = x:rs
dopcs (xs,rs) = dopcs $ (init &&& (:rs).last ) $ dblflipIt xs | 228Sorting algorithms/Pancake sort
| 8haskell
| 1gzps |
import Text.PhoneticCode.Soundex
main :: IO ()
main =
mapM_ print $
((,) <*> soundexSimple) <$> ["Soundex", "Example", "Sownteks", "Ekzampul"] | 224Soundex
| 8haskell
| oag8p |
from math import log
def getDigit(num, base, digit_num):
return (num
def makeBlanks(size):
return [ [] for i in range(size) ]
def split(a_list, base, digit_num):
buckets = makeBlanks(base)
for num in a_list:
buckets[getDigit(num, base, digit_num)].append(num)
return buckets
def merge(a_list):
new_list = []
for sublist in a_list:
new_list.extend(sublist)
return new_list
def maxAbs(a_list):
return max(abs(num) for num in a_list)
def split_by_sign(a_list):
buckets = [[], []]
for num in a_list:
if num < 0:
buckets[0].append(num)
else:
buckets[1].append(num)
return buckets
def radixSort(a_list, base):
passes = int(round(log(maxAbs(a_list), base)) + 1)
new_list = list(a_list)
for digit_num in range(passes):
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list)) | 225Sorting algorithms/Radix sort
| 3python
| dx7n1 |
permutationsort <- function(x)
{
if(!require(e1071) stop("the package e1071 is required")
is.sorted <- function(x) all(diff(x) >= 0)
perms <- permutations(length(x))
i <- 1
while(!is.sorted(x))
{
x <- x[perms[i,]]
i <- i + 1
}
x
}
permutationsort(c(1, 10, 9, 7, 3, 0)) | 222Sorting algorithms/Permutation sort
| 13r
| 2z8lg |
sub stooge {
use integer;
my ($x, $i, $j) = @_;
$i //= 0;
$j //= $
if ( $x->[$j] < $x->[$i] ) {
@$x[$i, $j] = @$x[$j, $i];
}
if ( $j - $i > 1 ) {
my $t = ($j - $i + 1) / 3;
stooge( $x, $i, $j - $t );
stooge( $x, $i + $t, $j );
stooge( $x, $i, $j - $t );
}
}
my @a = map (int rand(100), 1 .. 10);
print "Before @a\n";
stooge(\@a);
print "After @a\n"; | 221Sorting algorithms/Stooge sort
| 2perl
| cf09a |
function insertion_sort ()
{
local -a arr
local -i i
local -i j
local -i key
local -i prev
local -i leftval
local -i N
arr=( $@ )
N=${
readonly N
for (( i=1; i<$N; i++ ))
do
key=$((arr[$i]))
prev=$((arr[$i-1]))
j=$i
while [ $j -gt 0 ] && [ $key -lt $prev ]
do
arr[$j]=$((arr[$j-1]))
j=$(($j-1))
prev=$((arr[$j-1]))
done
arr[$j]=$(($key))
done
echo ${arr[*]}
}
function main ()
{
declare -a sorted
if [ $
arr=(10 8 20 100 -3 12 4 -5 32 0 1)
else
arr=($@)
fi
echo
echo "original"
echo -e "\t ${arr[*]} \n"
sorted=($(insertion_sort ${arr[*]}))
echo
echo "sorted:"
echo -e "\t ${sorted[*]} \n"
}
if [[ "$0" == "bash" ]]; then
unset main
else
main "$@"
fi | 229Sorting algorithms/Insertion sort
| 4bash
| 387zx |
public class PancakeSort
{
int[] heap;
public String toString() {
String info = "";
for (int x: heap)
info += x + " ";
return info;
}
public void flip(int n) {
for (int i = 0; i < (n+1) / 2; ++i) {
int tmp = heap[i];
heap[i] = heap[n-i];
heap[n-i] = tmp;
}
System.out.println("flip(0.." + n + "): " + toString());
}
public int[] minmax(int n) {
int xm, xM;
xm = xM = heap[0];
int posm = 0, posM = 0;
for (int i = 1; i < n; ++i) {
if (heap[i] < xm) {
xm = heap[i];
posm = i;
}
else if (heap[i] > xM) {
xM = heap[i];
posM = i;
}
}
return new int[] {posm, posM};
}
public void sort(int n, int dir) {
if (n == 0) return;
int[] mM = minmax(n);
int bestXPos = mM[dir];
int altXPos = mM[1-dir];
boolean flipped = false;
if (bestXPos == n-1) {
--n;
}
else if (bestXPos == 0) {
flip(n-1);
--n;
}
else if (altXPos == n-1) {
dir = 1-dir;
--n;
flipped = true;
}
else {
flip(bestXPos);
}
sort(n, dir);
if (flipped) {
flip(n);
}
}
PancakeSort(int[] numbers) {
heap = numbers;
sort(numbers.length, 1);
}
public static void main(String[] args) {
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; ++i)
numbers[i] = Integer.valueOf(args[i]);
PancakeSort pancakes = new PancakeSort(numbers);
System.out.println(pancakes);
}
} | 228Sorting algorithms/Pancake sort
| 9java
| 7lorj |
void quicksort(int *A, int len);
int main (void) {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++) {
printf(, a[i]);
}
printf();
quicksort(a, n);
for (i = 0; i < n; i++) {
printf(, a[i]);
}
printf();
return 0;
}
void quicksort(int *A, int len) {
if (len < 2) return;
int pivot = A[len / 2];
int i, j;
for (i = 0, j = len - 1; ; i++, j--) {
while (A[i] < pivot) i++;
while (A[j] > pivot) j--;
if (i >= j) break;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
quicksort(A, i);
quicksort(A + i, len - i);
} | 230Sorting algorithms/Quicksort
| 5c
| v3a2o |
Array.prototype.pancake_sort = function () {
for (var i = this.length - 1; i >= 1; i--) { | 228Sorting algorithms/Pancake sort
| 10javascript
| p4tb7 |
function stoogeSort(&$arr, $i, $j)
{
if($arr[$j] < $arr[$i])
{
list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
}
if(($j - $i) > 1)
{
$t = ($j - $i + 1) / 3;
stoogesort($arr, $i, $j - $t);
stoogesort($arr, $i + $t, $j);
stoogesort($arr, $i, $j - $t);
}
} | 221Sorting algorithms/Stooge sort
| 12php
| xh5w5 |
package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
selectionSort(a)
fmt.Println("after: ", a)
}
func selectionSort(a []int) {
last := len(a) - 1
for i := 0; i < last; i++ {
aMin := a[i]
iMin := i
for j := i + 1; j < len(a); j++ {
if a[j] < aMin {
aMin = a[j]
iMin = j
}
}
a[i], a[iMin] = aMin, a[i]
}
} | 226Sorting algorithms/Selection sort
| 0go
| 7lnr2 |
class Array
def permutationsort
permutation.each{|perm| return perm if perm.sorted?}
end
def sorted?
each_cons(2).all? {|a, b| a <= b}
end
end | 222Sorting algorithms/Permutation sort
| 14ruby
| rctgs |
import Data.List (delete)
selSort :: (Ord a) => [a] -> [a]
selSort [] = []
selSort xs = selSort (delete x xs) ++ [x]
where x = maximum xs | 226Sorting algorithms/Selection sort
| 8haskell
| 81u0z |
public static void main(String[] args){
System.out.println(soundex("Soundex"));
System.out.println(soundex("Example"));
System.out.println(soundex("Sownteks"));
System.out.println(soundex("Ekzampul"));
}
private static String getCode(char c){
switch(c){
case 'B': case 'F': case 'P': case 'V':
return "1";
case 'C': case 'G': case 'J': case 'K':
case 'Q': case 'S': case 'X': case 'Z':
return "2";
case 'D': case 'T':
return "3";
case 'L':
return "4";
case 'M': case 'N':
return "5";
case 'R':
return "6";
default:
return "";
}
}
public static String soundex(String s){
String code, previous, soundex;
code = s.toUpperCase().charAt(0) + ""; | 224Soundex
| 9java
| wjlej |
sub spiral
{my ($n, $x, $y, $dx, $dy, @a) = (shift, 0, 0, 1, 0);
foreach (0 .. $n**2 - 1)
{$a[$y][$x] = $_;
my ($nx, $ny) = ($x + $dx, $y + $dy);
($dx, $dy) =
$dx == 1 && ($nx == $n || defined $a[$ny][$nx])
? ( 0, 1)
: $dy == 1 && ($ny == $n || defined $a[$ny][$nx])
? (-1, 0)
: $dx == -1 && ($nx < 0 || defined $a[$ny][$nx])
? ( 0, -1)
: $dy == -1 && ($ny < 0 || defined $a[$ny][$nx])
? ( 1, 0)
: ($dx, $dy);
($x, $y) = ($x + $dx, $y + $dy);}
return @a;}
foreach (spiral 5)
{printf "%3d", $_ foreach @$_;
print "\n";} | 218Spiral matrix
| 2perl
| u6tvr |
class Array
def radix_sort(base=10)
ary = dup
rounds = (Math.log(ary.minmax.map(&:abs).max)/Math.log(base)).floor + 1
rounds.times do |i|
buckets = Array.new(2*base){[]}
base_i = base**i
ary.each do |n|
digit = (n/base_i) % base
digit += base if 0<=n
buckets[digit] << n
end
ary = buckets.flatten
p [i, ary] if $DEBUG
end
ary
end
def radix_sort!(base=10)
replace radix_sort(base)
end
end
p [1, 3, 8, 9, 0, 0, 8, 7, 1, 6].radix_sort
p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort
p [170, 45, 75, 90, 2, 24, -802, -66].radix_sort
p [100000, -10000, 400, 23, 10000].radix_sort | 225Sorting algorithms/Radix sort
| 14ruby
| tshf2 |
fun pancakeSort(a: IntArray) {
fun indexOfMax(n: Int): Int = (0 until n).maxByOrNull{ a[it] }!!
fun flip(index: Int) {
a.reverse(0, index + 1)
}
for (n in a.size downTo 2) { | 228Sorting algorithms/Pancake sort
| 11kotlin
| u6xvc |
null | 228Sorting algorithms/Pancake sort
| 1lua
| 5yqu6 |
var soundex = function (s) {
var a = s.toLowerCase().split('')
f = a.shift(),
r = '',
codes = {
a: '', e: '', i: '', o: '', u: '',
b: 1, f: 1, p: 1, v: 1,
c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2,
d: 3, t: 3,
l: 4,
m: 5, n: 5,
r: 6
};
r = f +
a
.map(function (v, i, a) { return codes[v] })
.filter(function (v, i, a) { return ((i === 0) ? v !== codes[f] : v !== a[i - 1]); })
.join('');
return (r + '000').slice(0, 4).toUpperCase();
};
var tests = {
"Soundex": "S532",
"Example": "E251",
"Sownteks": "S532",
"Ekzampul": "E251",
"Euler": "E460",
"Gauss": "G200",
"Hilbert": "H416",
"Knuth": "K530",
"Lloyd": "L300",
"Lukasiewicz": "L222",
"Ellery": "E460",
"Ghosh": "G200",
"Heilbronn": "H416",
"Kant": "K530",
"Ladd": "L300",
"Lissajous": "L222",
"Wheaton": "W350",
"Ashcraft": "A226",
"Burroughs": "B622",
"Burrows": "B620",
"O'Hara": "O600"
};
for (var i in tests)
if (tests.hasOwnProperty(i)) {
console.log(
i +
' \t' +
tests[i] +
'\t' +
soundex(i) +
'\t' +
(soundex(i) === tests[i])
);
} | 224Soundex
| 10javascript
| 8140l |
sub shell_sort {
my (@a, $h, $i, $j, $k) = @_;
for ($h = @a; $h = int $h / 2;) {
for $i ($h .. $
$k = $a[$i];
for ($j = $i; $j >= $h && $k < $a[$j - $h]; $j -= $h) {
$a[$j] = $a[$j - $h];
}
$a[$j] = $k;
}
}
@a;
}
my @a = map int rand 100, 1 .. $ARGV[0] || 10;
say "@a";
@a = shell_sort @a;
say "@a"; | 223Sorting algorithms/Shell sort
| 2perl
| b5yk4 |
fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) {
let (left, right) = out.split_at_mut(in1.len());
left.clone_from_slice(in1);
right.clone_from_slice(in2);
} | 225Sorting algorithms/Radix sort
| 15rust
| z0kto |
object RadixSort extends App {
def sort(toBeSort: Array[Int]): Array[Int] = { | 225Sorting algorithms/Radix sort
| 16scala
| yi163 |
(defn qsort [L]
(if (empty? L)
'()
(let [[pivot & L2] L]
(lazy-cat (qsort (for [y L2 :when (< y pivot)] y))
(list pivot)
(qsort (for [y L2 :when (>= y pivot)] y)))))) | 230Sorting algorithms/Quicksort
| 6clojure
| rcsg2 |
sub patience_sort {
my @s = [shift];
for my $card (@_) {
my @t = grep { $_->[-1] > $card } @s;
if (@t) { push @{shift(@t)}, $card }
else { push @s, [$card] }
}
my @u;
while (my @v = grep @$_, @s) {
my $value = (my $min = shift @v)->[-1];
for (@v) {
($min, $value) =
($_, $_->[-1]) if $_->[-1] < $value
}
push @u, pop @$min;
}
return @u
}
print join ' ', patience_sort qw(4 3 6 2 -1 13 12 9); | 227Sorting algorithms/Patience sort
| 2perl
| sblq3 |
void insertion_sort(int*, const size_t);
void insertion_sort(int *a, const size_t n) {
for(size_t i = 1; i < n; ++i) {
int key = a[i];
size_t j = i;
while( (j > 0) && (key < a[j - 1]) ) {
a[j] = a[j - 1];
--j;
}
a[j] = key;
}
}
int main (int argc, char** argv) {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
const size_t n = sizeof(a) / sizeof(a[0]) ;
for (size_t i = 0; i < n; i++)
printf(, a[i], (i == (n - 1))? : );
insertion_sort(a, n);
for (size_t i = 0; i < n; i++)
printf(, a[i], (i == (n - 1))? : );
return 0;
} | 229Sorting algorithms/Insertion sort
| 5c
| yih6f |
>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1)
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10] | 221Sorting algorithms/Stooge sort
| 3python
| lt8cv |
stoogesort = function(vect) {
i = 1
j = length(vect)
if(vect[j] < vect[i]) vect[c(j, i)] = vect[c(i, j)]
if(j - i > 1) {
t = (j - i + 1)%/% 3
vect[i:(j - t)] = stoogesort(vect[i:(j - t)])
vect[(i + t):j] = stoogesort(vect[(i + t):j])
vect[i:(j - t)] = stoogesort(vect[i:(j - t)])
}
vect
}
v = sample(21, 20)
k = stoogesort(v)
v
k | 221Sorting algorithms/Stooge sort
| 13r
| yix6h |
public static void sort(int[] nums){
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
int smallest = Integer.MAX_VALUE;
int smallestAt = currentPlace+1;
for(int check = currentPlace; check<nums.length;check++){
if(nums[check]<smallest){
smallestAt = check;
smallest = nums[check];
}
}
int temp = nums[currentPlace];
nums[currentPlace] = nums[smallestAt];
nums[smallestAt] = temp;
}
} | 226Sorting algorithms/Selection sort
| 9java
| e7ma5 |
null | 224Soundex
| 11kotlin
| b56kb |
function shellSort($arr)
{
$inc = round(count($arr)/2);
while($inc > 0)
{
for($i = $inc; $i < count($arr);$i++){
$temp = $arr[$i];
$j = $i;
while($j >= $inc && $arr[$j-$inc] > $temp)
{
$arr[$j] = $arr[$j - $inc];
$j -= $inc;
}
$arr[$j] = $temp;
}
$inc = round($inc/2.2);
}
return $arr;
} | 223Sorting algorithms/Shell sort
| 12php
| 6oa3g |
<?php
class PilesHeap extends SplMinHeap {
public function compare($pile1, $pile2) {
return parent::compare($pile1->top(), $pile2->top());
}
}
function patience_sort(&$n) {
$piles = array();
foreach ($n as $x) {
$low = 0; $high = count($piles)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($piles[$mid]->top() >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
if ($i == count($piles))
$piles[] = new SplStack();
$piles[$i]->push($x);
}
$heap = new PilesHeap();
foreach ($piles as $pile)
$heap->insert($pile);
for ($c = 0; $c < count($n); $c++) {
$smallPile = $heap->extract();
$n[$c] = $smallPile->pop();
if (!$smallPile->isEmpty())
$heap->insert($smallPile);
}
assert($heap->isEmpty());
}
$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?> | 227Sorting algorithms/Patience sort
| 12php
| u6qv5 |
function selectionSort(nums) {
var len = nums.length;
for(var i = 0; i < len; i++) {
var minAt = i;
for(var j = i + 1; j < len; j++) {
if(nums[j] < nums[minAt])
minAt = j;
}
if(minAt != i) {
var temp = nums[i];
nums[i] = nums[minAt];
nums[minAt] = temp;
}
}
return nums;
} | 226Sorting algorithms/Selection sort
| 10javascript
| 0pvsz |
local d, digits, alpha = '01230120022455012623010202', {}, ('A'):byte()
d:gsub(".",function(c)
digits[string.char(alpha)] = c
alpha = alpha + 1
end)
function soundex(w)
local res = {}
for c in w:upper():gmatch'.'do
local d = digits[c]
if d then
if #res==0 then
res[1] = c
elseif #res==1 or d~= res[#res] then
res[1+#res] = d
end
end
end
if #res == 0 then
return '0000'
else
res = table.concat(res):gsub("0",'')
return (res .. '0000'):sub(1,4)
end
end | 224Soundex
| 1lua
| p4ybw |
(defn insertion-sort [coll]
(reduce (fn [result input]
(let [[less more] (split-with #(< % input) result)]
(concat less [input] more)))
[]
coll)) | 229Sorting algorithms/Insertion sort
| 6clojure
| 2zal1 |
int max (int *a, int n, int i, int j, int k) {
int m = i;
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
void downheap (int *a, int n, int i) {
while (1) {
int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
if (j == i) {
break;
}
int t = a[i];
a[i] = a[j];
a[j] = t;
i = j;
}
}
void heapsort (int *a, int n) {
int i;
for (i = (n - 2) / 2; i >= 0; i--) {
downheap(a, n, i);
}
for (i = 0; i < n; i++) {
int t = a[n - i - 1];
a[n - i - 1] = a[0];
a[0] = t;
downheap(a, n - i - 1, 0);
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf(, a[i], i == n - 1 ? : );
heapsort(a, n);
for (i = 0; i < n; i++)
printf(, a[i], i == n - 1 ? : );
return 0;
} | 231Sorting algorithms/Heapsort
| 5c
| u6av4 |
class Array
def stoogesort
self.dup.stoogesort!
end
def stoogesort!(i = 0, j = self.length-1)
if self[j] < self[i]
self[i], self[j] = self[j], self[i]
end
if j - i > 1
t = (j - i + 1)/3
stoogesort!(i, j-t)
stoogesort!(i+t, j)
stoogesort!(i, j-t)
end
self
end
end
p [1,4,5,3,-6,3,7,10,-2,-5].stoogesort | 221Sorting algorithms/Stooge sort
| 14ruby
| v3i2n |
fun <T : Comparable<T>> Array<T>.selection_sort() {
for (i in 0..size - 2) {
var k = i
for (j in i + 1..size - 1)
if (this[j] < this[k])
k = j
if (k != i) {
val tmp = this[i]
this[i] = this[k]
this[k] = tmp
}
}
}
fun main(args: Array<String>) {
val i = arrayOf(4, 9, 3, -2, 0, 7, -5, 1, 6, 8)
i.selection_sort()
println(i.joinToString())
val s = Array(i.size, { -i[it].toShort() })
s.selection_sort()
println(s.joinToString())
val c = arrayOf('z', 'h', 'd', 'c', 'a')
c.selection_sort()
println(c.joinToString())
} | 226Sorting algorithms/Selection sort
| 11kotlin
| kuth3 |
def shell(seq):
inc = len(seq)
while inc:
for i, el in enumerate(seq[inc:], inc):
while i >= inc and seq[i - inc] > el:
seq[i] = seq[i - inc]
i -= inc
seq[i] = el
inc = 1 if inc == 2 else inc * 5 | 223Sorting algorithms/Shell sort
| 3python
| p4mbm |
from functools import total_ordering
from bisect import bisect_left
from heapq import merge
@total_ordering
class Pile(list):
def __lt__(self, other): return self[-1] < other[-1]
def __eq__(self, other): return self[-1] == other[-1]
def patience_sort(n):
piles = []
for x in n:
new_pile = Pile([x])
i = bisect_left(piles, new_pile)
if i != len(piles):
piles[i].append(x)
else:
piles.append(new_pile)
n[:] = merge(*[reversed(pile) for pile in piles])
if __name__ == :
a = [4, 65, 2, -31, 0, 99, 83, 782, 1]
patience_sort(a)
print a | 227Sorting algorithms/Patience sort
| 3python
| 0p2sq |
fn stoogesort<E>(a: &mut [E])
where E: PartialOrd
{
let len = a.len();
if a.first().unwrap() > a.last().unwrap() {
a.swap(0, len - 1);
}
if len - 1 > 1 {
let t = len / 3;
stoogesort(&mut a[..len - 1]);
stoogesort(&mut a[t..]);
stoogesort(&mut a[..len - 1]);
}
}
fn main() {
let mut numbers = vec![1_i32, 9, 4, 7, 6, 5, 3, 2, 8];
println!("Before: {:?}", &numbers);
stoogesort(&mut numbers);
println!("After: {:?}", &numbers);
} | 221Sorting algorithms/Stooge sort
| 15rust
| u6nvj |
object StoogeSort extends App {
def stoogeSort(a: Array[Int], 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)
}
}
val a = Array(100, 2, 56, 200, -52, 3, 99, 33, 177, -199)
println(s"Original: ${a.mkString(", ")}")
stoogeSort(a, 0, a.length - 1)
println(s"Sorted : ${a.mkString(", ")}")
} | 221Sorting algorithms/Stooge sort
| 16scala
| g9t4i |
def spiral(n):
dx,dy = 1,0
x,y = 0,0
myarray = [[None]* n for j in range(n)]
for i in xrange(n**2):
myarray[x][y] = i
nx,ny = x+dx, y+dy
if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
x,y = nx,ny
else:
dx,dy = -dy,dx
x,y = x+dx, y+dy
return myarray
def printspiral(myarray):
n = range(len(myarray))
for y in n:
for x in n:
print % myarray[x][y],
print
printspiral(spiral(5)) | 218Spiral matrix
| 3python
| 5yzux |
(defn- swap [a i j]
(assoc a i (nth a j) j (nth a i)))
(defn- sift [a pred k l]
(loop [a a x k y (inc (* 2 k))]
(if (< (inc (* 2 x)) l)
(let [ch (if (and (< y (dec l)) (pred (nth a y) (nth a (inc y))))
(inc y)
y)]
(if (pred (nth a x) (nth a ch))
(recur (swap a x ch) ch (inc (* 2 ch)))
a))
a)))
(defn- heapify[pred a len]
(reduce (fn [c term] (sift (swap c term 0) pred 0 term))
(reduce (fn [c i] (sift c pred i len))
(vec a)
(range (dec (int (/ len 2))) -1 -1))
(range (dec len) 0 -1)))
(defn heap-sort
([a pred]
(let [len (count a)]
(heapify pred a len)))
([a]
(heap-sort a <))) | 231Sorting algorithms/Heapsort
| 6clojure
| 7lsr0 |
sub pancake {
my @x = @_;
for my $idx (0 .. $
my $min = $idx;
$x[$min] > $x[$_] and $min = $_ for $idx + 1 .. $
next if $x[$min] == $x[$idx];
@x[$min .. $
@x[$idx .. $
}
@x;
}
my @a = map (int rand(100), 1 .. 10);
print "Before @a\n";
@a = pancake(@a);
print "After @a\n"; | 228Sorting algorithms/Pancake sort
| 2perl
| 8120w |
function SelectionSort( f )
for k = 1, #f-1 do
local idx = k
for i = k+1, #f do
if f[i] < f[idx] then
idx = i
end
end
f[k], f[idx] = f[idx], f[k]
end
end
f = { 15, -3, 0, -1, 5, 4, 5, 20, -8 }
SelectionSort( f )
for i in next, f do
print( f[i] )
end | 226Sorting algorithms/Selection sort
| 1lua
| b5zka |
void merge (int *a, int n, int m) {
int i, j, k;
int *x = malloc(n * sizeof (int));
for (i = 0, j = m, k = 0; k < n; k++) {
x[k] = j == n ? a[i++]
: i == m ? a[j++]
: a[j] < a[i] ? a[j++]
: a[i++];
}
for (i = 0; i < n; i++) {
a[i] = x[i];
}
free(x);
}
void merge_sort (int *a, int n) {
if (n < 2)
return;
int m = n / 2;
merge_sort(a, m);
merge_sort(a + m, n - m);
merge(a, n, m);
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf(, a[i], i == n - 1 ? : );
merge_sort(a, n);
for (i = 0; i < n; i++)
printf(, a[i], i == n - 1 ? : );
return 0;
} | 232Sorting algorithms/Merge sort
| 5c
| g9w45 |
func stoogeSort(inout arr:[Int], _ i:Int = 0, var _ j:Int = -1) {
if j == -1 {
j = arr.count - 1
}
if arr[i] > arr[j] {
swap(&arr[i], &arr[j])
}
if j - i > 1 {
let t = (j - i + 1) / 3
stoogeSort(&arr, i, j - t)
stoogeSort(&arr, i + t, j)
stoogeSort(&arr, i, j - t)
}
}
var a = [-4, 2, 5, 2, 3, -2, 1, 100, 20]
stoogeSort(&a)
println(a) | 221Sorting algorithms/Stooge sort
| 17swift
| 2zolj |
class Array
def shellsort!
inc = length / 2
while inc!= 0
inc.step(length-1) do |i|
el = self[i]
while i >= inc and self[i - inc] > el
self[i] = self[i - inc]
i -= inc
end
self[i] = el
end
inc = (inc == 2? 1: (inc * 5.0 / 11).to_i)
end
self
end
end
data = [22, 7, 2, -5, 8, 4]
data.shellsort!
p data | 223Sorting algorithms/Shell sort
| 14ruby
| arc1s |
spiral <- function(n) matrix(order(cumsum(rep(rep_len(c(1, n, -1, -n), 2 * n - 1), n - seq(2 * n - 1) %/% 2))), n, byrow = T) - 1
spiral(5) | 218Spiral matrix
| 13r
| ltnce |
quickSort(List a) {
if (a.length <= 1) {
return a;
}
var pivot = a[0];
var less = [];
var more = [];
var pivotList = []; | 230Sorting algorithms/Quicksort
| 18dart
| yij65 |
fn shell_sort<T: Ord + Copy>(v: &mut [T]) {
let mut gap = v.len() / 2;
let len = v.len();
while gap > 0 {
for i in gap..len {
let temp = v[i];
let mut j = i;
while j >= gap && v[j - gap] > temp {
v[j] = v[j - gap];
j -= gap;
}
v[j] = temp;
}
gap /= 2;
}
}
fn main() {
let mut numbers = [4i32, 65, 2, -31, 0, 99, 2, 83, 782, 1];
println!("Before: {:?}", numbers);
shell_sort(&mut numbers);
println!("After: {:?}", numbers);
} | 223Sorting algorithms/Shell sort
| 15rust
| e7laj |
insertSort(List<int> array){
for(int i = 1; i < array.length; i++){
int value = array[i];
int j = i - 1;
while(j >= 0 && array[j] > value){
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = value;
}
return array;
}
void main() {
List<int> a = insertSort([10, 3, 11, 15, 19, 1]);
print('${a}');
} | 229Sorting algorithms/Insertion sort
| 18dart
| dx5nj |
object ShellSort {
def incSeq(len:Int)=new Iterator[Int]{
private[this] var x:Int=len/2
def hasNext=x>0
def next()={x=if (x==2) 1 else x*5/11; x}
}
def InsertionSort(a:Array[Int], inc:Int)={
for (i <- inc until a.length; temp=a(i)){
var j=i;
while (j>=inc && a(j-inc)>temp){
a(j)=a(j-inc)
j=j-inc
}
a(j)=temp
}
}
def shellSort(a:Array[Int])=for(inc<-incSeq(a.length)) InsertionSort(a, inc)
def main(args: Array[String]): Unit = {
var a=Array(2, 5, 3, 4, 3, 9, 3, 2, 5, 4, 1, 3, 22, 7, 2, -5, 8, 4)
println(a.mkString(","))
shellSort(a)
println(a.mkString(","))
}
} | 223Sorting algorithms/Shell sort
| 16scala
| qkuxw |
class Array
def patience_sort
piles = []
each do |i|
if (idx = piles.index{|pile| pile.last <= i})
piles[idx] << i
else
piles << [i]
end
end
result = []
until piles.empty?
first = piles.map(&:first)
idx = first.index(first.min)
result << piles[idx].shift
piles.delete_at(idx) if piles[idx].empty?
end
result
end
end
a = [4, 65, 2, -31, 0, 99, 83, 782, 1]
p a.patience_sort | 227Sorting algorithms/Patience sort
| 14ruby
| oau8v |
(defn merge [left right]
(cond (nil? left) right
(nil? right) left
:else (let [[l & *left] left
[r & *right] right]
(if (<= l r) (cons l (merge *left right))
(cons r (merge left *right))))))
(defn merge-sort [list]
(if (< (count list) 2)
list
(let [[left right] (split-at (/ (count list) 2) list)]
(merge (merge-sort left) (merge-sort right))))) | 232Sorting algorithms/Merge sort
| 6clojure
| ku8hs |
use Text::Soundex;
print soundex("Soundex"), "\n";
print soundex("Example"), "\n";
print soundex("Sownteks"), "\n";
print soundex("Ekzampul"), "\n"; | 224Soundex
| 2perl
| 6o136 |
import scala.collection.mutable
object PatienceSort extends App {
def sort[A](source: Iterable[A])(implicit bound: A => Ordered[A]): Iterable[A] = {
val piles = mutable.ListBuffer[mutable.Stack[A]]()
def PileOrdering: Ordering[mutable.Stack[A]] =
(a: mutable.Stack[A], b: mutable.Stack[A]) => b.head.compare(a.head) | 227Sorting algorithms/Patience sort
| 16scala
| fqrd4 |
void heapSort(List a) {
int count = a.length; | 231Sorting algorithms/Heapsort
| 18dart
| mnjyb |
tutor = False
def pancakesort(data):
if len(data) <= 1:
return data
if tutor: print()
for size in range(len(data), 1, -1):
maxindex = max(range(size), key=data.__getitem__)
if maxindex+1 != size:
if maxindex != 0:
if tutor: print('With:%r doflip %i'
% ( ' '.join(str(x) for x in data), maxindex+1 ))
data[:maxindex+1] = reversed(data[:maxindex+1])
if tutor: print('With:%r doflip%i'
% ( ' '.join(str(x) for x in data), size ))
data[:size] = reversed(data[:size])
if tutor: print() | 228Sorting algorithms/Pancake sort
| 3python
| oav81 |
func shellsort<T where T: Comparable>(inout seq: [T]) {
var inc = seq.count / 2
while inc > 0 {
for (var i, el) in EnumerateSequence(seq) {
while i >= inc && seq[i - inc] > el {
seq[i] = seq[i - inc]
i -= inc
}
seq[i] = el
}
if inc == 2 {
inc = 1
} else {
inc = inc * 5 / 11
}
}
} | 223Sorting algorithms/Shell sort
| 17swift
| 1g9pt |
<?php
echo soundex(), ;
echo soundex(), ;
echo soundex(), ;
echo soundex(), ;
?> | 224Soundex
| 12php
| 1gmpq |
def spiral(n)
spiral = Array.new(n) {Array.new(n, nil)}
runs = n.downto(0).each_cons(2).to_a.flatten
delta = [[1,0], [0,1], [-1,0], [0,-1]].cycle
x, y, value = -1, 0, -1
for run in runs
dx, dy = delta.next
run.times { spiral[y+=dy][x+=dx] = (value+=1) }
end
spiral
end
def print_matrix(m)
width = m.flatten.map{|x| x.to_s.size}.max
m.each {|row| puts row.map {|x| % x}.join}
end
print_matrix spiral(5) | 218Spiral matrix
| 14ruby
| g964q |
const VECTORS: [(isize, isize); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)];
pub fn spiral_matrix(size: usize) -> Vec<Vec<u32>> {
let mut matrix = vec![vec![0; size]; size];
let mut movement = VECTORS.iter().cycle();
let (mut x, mut y, mut n) = (-1, 0, 1..);
for (move_x, move_y) in std::iter::once(size)
.chain((1..size).rev().flat_map(|n| std::iter::repeat(n).take(2)))
.flat_map(|steps| std::iter::repeat(movement.next().unwrap()).take(steps))
{
x += move_x;
y += move_y;
matrix[y as usize][x as usize] = n.next().unwrap();
}
matrix
}
fn main() {
for i in spiral_matrix(4).iter() {
for j in i.iter() {
print!("{:>2} ", j);
}
println!();
}
} | 218Spiral matrix
| 15rust
| rcyg5 |
sub empty{ not @_ } | 212Stack
| 2perl
| fq8d7 |
class Folder(){
var dir = (1,0)
var pos = (-1,0)
def apply(l:List[Int], a:Array[Array[Int]]) = {
var (x,y) = pos | 218Spiral matrix
| 16scala
| hvcja |
class Array
def pancake_sort!
num_flips = 0
(self.size-1).downto(1) do |end_idx|
max = self[0..end_idx].max
max_idx = self[0..end_idx].index(max)
next if max_idx == end_idx
if max_idx > 0
self[0..max_idx] = self[0..max_idx].reverse
p [num_flips += 1, self] if $DEBUG
end
self[0..end_idx] = self[0..end_idx].reverse
p [num_flips += 1, self] if $DEBUG
end
self
end
end
p a = (1..9).to_a.shuffle
p a.pancake_sort! | 228Sorting algorithms/Pancake sort
| 14ruby
| nw5it |
fn pancake_sort<T: Ord>(v: &mut [T]) {
let len = v.len(); | 228Sorting algorithms/Pancake sort
| 15rust
| dx4ny |
$stack = array();
empty( $stack );
array_push( $stack, 1 );
array_push( $stack, 2 );
empty( $stack );
echo array_pop( $stack );
echo array_pop( $stack ); | 212Stack
| 12php
| hv4jf |
void main() {
MergeSortInDart sampleSort = MergeSortInDart();
List<int> theResultingList = sampleSort.sortTheList([54, 89, 125, 47899, 32, 61, 42, 895647, 215, 345, 6, 21, 2, 78]);
print('Here\'s the sorted list: ${theResultingList}');
} | 232Sorting algorithms/Merge sort
| 18dart
| ltkct |
import Foundation
struct PancakeSort {
var arr:[Int]
mutating func flip(n:Int) {
for i in 0 ..< (n + 1) / 2 {
swap(&arr[n - i], &arr[i])
}
println("flip(0.. \(n)): \(arr)")
}
func minmax(n:Int) -> [Int] {
var xm = arr[0]
var xM = arr[0]
var posm = 0
var posM = 0
for i in 1..<n {
if (arr[i] < xm) {
xm = arr[i]
posm = i
} else if (arr[i] > xM) {
xM = arr[i]
posM = i
}
}
return [posm, posM]
}
mutating func sort(var n:Int, var dir:Int) {
if n == 0 {
return
}
let mM = minmax(n)
let bestXPos = mM[dir]
let altXPos = mM[1 - dir]
var flipped = false
if bestXPos == n - 1 {
n--
} else if bestXPos == 0 {
flip(n - 1)
n--
} else if altXPos == n - 1 {
dir = 1 - dir
n--
flipped = true
} else {
flip(bestXPos)
}
sort(n, dir: dir)
if flipped {
flip(n)
}
}
}
let arr = [2, 3, 6, 1, 4, 5, 10, 8, 7, 9]
var a = PancakeSort(arr: arr)
a.sort(arr.count, dir: 1)
println(a.arr) | 228Sorting algorithms/Pancake sort
| 17swift
| ieuo0 |
sub selection_sort
{my @a = @_;
foreach my $i (0 .. $
{my $min = $i + 1;
$a[$_] < $a[$min] and $min = $_ foreach $min .. $
$a[$i] > $a[$min] and @a[$i, $min] = @a[$min, $i];}
return @a;} | 226Sorting algorithms/Selection sort
| 2perl
| 38kzs |
from itertools import groupby
def soundex(word):
codes = (,, , , , )
soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)
cmap2 = lambda kar: soundDict.get(kar, '9')
sdx = ''.join(cmap2(kar) for kar in word.lower())
sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')
sdx3 = sdx2[0:4].ljust(4,'0')
return sdx3 | 224Soundex
| 3python
| yia6q |
function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
$min = $i;
for($j = $i + 1; $j < $n; $j++){
if($arr[$j] < $arr[$min]){
$min = $j;
}
}
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
} | 226Sorting algorithms/Selection sort
| 12php
| p43ba |
package main
import (
"sort"
"container/heap"
"fmt"
)
type HeapHelper struct {
container sort.Interface
length int
}
func (self HeapHelper) Len() int { return self.length } | 231Sorting algorithms/Heapsort
| 0go
| 0pmsk |
def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } }
def siftDown = { a, start, end ->
def p = start
while (p*2 < end) {
def c = p*2 + ((p*2 + 1 < end && a[p*2 + 2] > a[p*2 + 1]) ? 2: 1)
if (checkSwap(a, c, p)) { p = c }
else { return }
}
}
def heapify = {
(((it.size()-2).intdiv(2))..0).each { start -> siftDown(it, start, it.size()-1) }
}
def heapSort = { list ->
heapify(list)
(0..<(list.size())).reverse().each { end ->
makeSwap(list, 0, end)
siftDown(list, 0, end-1)
}
list
} | 231Sorting algorithms/Heapsort
| 7groovy
| e7tal |
import Data.Graph.Inductive.Internal.Heap(
Heap(..),insert,findMin,deleteMin)
build :: Ord a => [(a,b)] -> Heap a b
build = foldr insert Empty
toList :: Ord a => Heap a b -> [(a,b)]
toList Empty = []
toList h = x:toList r
where (x,r) = (findMin h,deleteMin h)
heapsort :: Ord a => [a] -> [a]
heapsort = (map fst) . toList . build . map (\x->(x,x)) | 231Sorting algorithms/Heapsort
| 8haskell
| cfk94 |
class String
SoundexChars = 'BFPVCGJKQSXZDTLMNR'
SoundexNums = '111122222222334556'
SoundexCharsEx = '^' + SoundexChars
SoundexCharsDel = '^A-Z'
def soundex(census = true)
str = self.upcase.delete(SoundexCharsDel)
str[0,1] + str[1..-1].delete(SoundexCharsEx).
tr_s(SoundexChars, SoundexNums)\
[0 .. (census? 2: -1)].
ljust(3, '0') rescue ''
end
def sounds_like(other)
self.soundex == other.soundex
end
end
%w(Soundex Sownteks Example Ekzampul foo bar).each_slice(2) do |word1, word2|
[word1, word2].each {|word| puts '%-8s ->%s' % [word, word.soundex]}
print
print word1.sounds_like(word2)? :
print
end | 224Soundex
| 14ruby
| 9dwmz |
from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack | 212Stack
| 3python
| tsofw |
def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst | 226Sorting algorithms/Selection sort
| 3python
| 6ob3w |
package main
import "fmt"
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
quicksort(list)
fmt.Println("sorted! ", list)
}
func quicksort(a []int) {
var pex func(int, int)
pex = func(lower, upper int) {
for {
switch upper - lower {
case -1, 0: | 230Sorting algorithms/Quicksort
| 0go
| sbmqa |
package main
import "fmt"
func insertionSort(a []int) {
for i := 1; i < len(a); i++ {
value := a[i]
j := i - 1
for j >= 0 && a[j] > value {
a[j+1] = a[j]
j = j - 1
}
a[j+1] = value
}
}
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
insertionSort(list)
fmt.Println("sorted! ", list)
} | 229Sorting algorithms/Insertion sort
| 0go
| 1gtp5 |
selectionsort.loop <- function(x)
{
lenx <- length(x)
for(i in seq_along(x))
{
mini <- (i - 1) + which.min(x[i:lenx])
start_ <- seq_len(i-1)
x <- c(x[start_], x[mini], x[-c(start_, mini)])
}
x
} | 226Sorting algorithms/Selection sort
| 13r
| fq7dc |
def soundex(s:String)={
var code=s.head.toUpper.toString
var previous=getCode(code.head)
for(ch <- s.drop(1); current=getCode(ch.toUpper)){
if (!current.isEmpty && current!=previous)
code+=current
previous=current
}
code+="0000"
code.slice(0,4)
}
def getCode(c:Char)={
val code=Map("1"->List('B','F','P','V'),
"2"->List('C','G','J','K','Q','S','X','Z'),
"3"->List('D', 'T'),
"4"->List('L'),
"5"->List('M', 'N'),
"6"->List('R'))
code.find(_._2.exists(_==c)) match {
case Some((k,_)) => k
case _ => ""
}
} | 224Soundex
| 16scala
| v302s |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.