code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import System.Random
import Data.Array.IO
import Control.Monad
isSortedBy :: (a -> a -> Bool) -> [a] -> Bool
isSortedBy _ [] = True
isSortedBy f xs = all (uncurry f) . (zip <*> tail) $ xs
shuffle :: [a] -> IO [a]
shuffle xs = do
ar <- newArray n xs
forM [1..n] $ \i -> do
j <- randomRIO (i,n)
vi <- readArray ar i
vj <- readArray ar j
writeArray ar j vi
return vj
where
n = length xs
newArray :: Int -> [a] -> IO (IOArray Int a)
newArray n xs = newListArray (1,n) xs
bogosortBy :: (a -> a -> Bool) -> [a] -> IO [a]
bogosortBy f xs | isSortedBy f xs = return xs
| otherwise = shuffle xs >>= bogosortBy f
bogosort :: Ord a => [a] -> IO [a]
bogosort = bogosortBy (<) | 236Sorting algorithms/Bogosort
| 8haskell
| kuxh0 |
void swap(int *x, int *y) {
if(x == y)
return;
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
void cocktailsort(int *a, size_t n) {
while(1) {
char flag;
size_t start[2] = {1, n - 1},
end[2] = {n, 0},
inc[2] = {1, -1};
for(int it = 0; it < 2; ++it) {
flag = 1;
for(int i = start[it]; i != end[it]; i += inc[it])
if(a[i - 1] > a[i]) {
swap(a + i - 1, a + i);
flag = 0;
}
if(flag)
return;
}
}
}
int main(void) {
int a[] = { 5, -1, 101, -4, 0, 1, 8, 6, 2, 3 };
size_t n = sizeof(a)/sizeof(a[0]);
cocktailsort(a, n);
for (size_t i = 0; i < n; ++i)
printf(, a[i]);
return 0;
} | 240Sorting algorithms/Cocktail sort
| 5c
| mnlys |
import Data.Array
countingSort :: (Ix n) => [n] -> n -> n -> [n]
countingSort l lo hi = concatMap (uncurry $ flip replicate) count
where count = assocs . accumArray (+) 0 (lo, hi) . map (\i -> (i, 1)) $ l | 237Sorting algorithms/Counting sort
| 8haskell
| sbdqk |
function combsort(t)
local gapd, gap, swaps = 1.2473, #t, 0
while gap + swaps > 1 do
local k = 0
swaps = 0
if gap > 1 then gap = math.floor(gap / gapd) end
for k = 1, #t - gap do
if t[k] > t[k + gap] then
t[k], t[k + gap], swaps = t[k + gap], t[k], swaps + 1
end
end
end
return t
end
print(unpack(combsort{3,5,1,2,7,4,8,3,6,4,1})) | 235Sorting algorithms/Comb sort
| 1lua
| 6ou39 |
package main
import (
"fmt"
"math"
"sort"
"strings"
)
func sortedOutline(originalOutline []string, ascending bool) {
outline := make([]string, len(originalOutline))
copy(outline, originalOutline) | 241Sort an outline at every level
| 0go
| oan8q |
public static void countingSort(int[] array, int min, int max){
int[] count= new int[max - min + 1];
for(int number: array){
count[number - min]++;
}
int z= 0;
for(int i= min;i <= max;i++){
while(count[i - min] > 0){
array[z]= i;
z++;
count[i - min]--;
}
}
} | 237Sorting algorithms/Counting sort
| 9java
| 1gsp2 |
import Data.Tree (Tree(..), foldTree)
import qualified Data.Text.IO as T
import qualified Data.Text as T
import qualified Data.List as L
import Data.Bifunctor (first)
import Data.Ord (comparing)
import Data.Char (isSpace)
sortedOutline :: (Tree T.Text -> Tree T.Text -> Ordering)
-> T.Text
-> Either T.Text T.Text
sortedOutline cmp outlineText =
let xs = T.lines outlineText
in consistentIndentUnit (nonZeroIndents xs) >>=
\indentUnit ->
let forest = forestFromLineIndents $ indentLevelsFromLines xs
sortedForest =
subForest $
foldTree (\x xs -> Node x (L.sortBy cmp xs)) (Node "" forest)
in Right $ outlineFromForest indentUnit sortedForest
main :: IO ()
main =
mapM_ T.putStrLn $
concat $
[ \(comparatorLabel, cmp) ->
(\kv ->
let section = headedSection (fst kv) comparatorLabel
in (either (section . (" -> " <>)) section . sortedOutline cmp . snd)
kv) <$>
[ ("Four-spaced", spacedOutline)
, ("Tabbed", tabbedOutline)
, ("First unknown type", confusedOutline)
, ("Second unknown type", raggedOutline)
]
] <*>
[("(A -> Z)", comparing rootLabel), ("(Z -> A)", flip (comparing rootLabel))]
headedSection :: T.Text -> T.Text -> T.Text -> T.Text
headedSection outlineType comparatorName x =
T.concat ["\n", outlineType, " ", comparatorName, ":\n\n", x]
spacedOutline, tabbedOutline, confusedOutline, raggedOutline :: T.Text
spacedOutline =
"zeta\n\
\ beta\n\
\ gamma\n\
\ lambda\n\
\ kappa\n\
\ mu\n\
\ delta\n\
\alpha\n\
\ theta\n\
\ iota\n\
\ epsilon"
tabbedOutline =
"zeta\n\
\\tbeta\n\
\\tgamma\n\
\\t\tlambda\n\
\\t\tkappa\n\
\\t\tmu\n\
\\tdelta\n\
\alpha\n\
\\ttheta\n\
\\tiota\n\
\\tepsilon"
confusedOutline =
"zeta\n\
\ beta\n\
\ gamma\n\
\ lambda\n\
\ \t kappa\n\
\ mu\n\
\ delta\n\
\alpha\n\
\ theta\n\
\ iota\n\
\ epsilon"
raggedOutline =
"zeta\n\
\ beta\n\
\ gamma\n\
\ lambda\n\
\ kappa\n\
\ mu\n\
\ delta\n\
\alpha\n\
\ theta\n\
\ iota\n\
\ epsilon"
forestFromLineIndents :: [(Int, T.Text)] -> [Tree T.Text]
forestFromLineIndents = go
where
go [] = []
go ((n, s):xs) = Node s (go subOutline): go rest
where
(subOutline, rest) = span ((n <) . fst) xs
indentLevelsFromLines :: [T.Text] -> [(Int, T.Text)]
indentLevelsFromLines xs = first (`div` indentUnit) <$> pairs
where
pairs = first T.length . T.span isSpace <$> xs
indentUnit = maybe 1 fst (L.find ((0 <) . fst) pairs)
outlineFromForest :: T.Text -> [Tree T.Text] -> T.Text
outlineFromForest tabString forest = T.unlines $ forest >>= go ""
where
go indent node =
indent <> rootLabel node:
(subForest node >>= go (T.append tabString indent))
consistentIndentUnit :: [T.Text] -> Either T.Text T.Text
consistentIndentUnit prefixes = minimumIndent prefixes >>= checked prefixes
where
checked xs indentUnit
| all ((0 ==) . (`rem` unitLength) . T.length) xs = Right indentUnit
| otherwise =
Left
("Inconsistent indent depths: " <>
T.pack (show (T.length <$> prefixes)))
where
unitLength = T.length indentUnit
minimumIndent :: [T.Text] -> Either T.Text T.Text
minimumIndent prefixes = go $ T.foldr newChar "" $ T.concat prefixes
where
newChar c seen
| c `L.elem` seen = seen
| otherwise = c: seen
go cs
| 1 < length cs =
Left $ "Mixed indent characters used: " <> T.pack (show cs)
| otherwise = Right $ L.minimumBy (comparing T.length) prefixes
nonZeroIndents :: [T.Text] -> [T.Text]
nonZeroIndents textLines =
[ s
| x <- textLines
, s <- [T.takeWhile isSpace x]
, 0 /= T.length s ] | 241Sort an outline at every level
| 8haskell
| 2zull |
public class BogoSort
{
public static void main(String[] args)
{ | 236Sorting algorithms/Bogosort
| 9java
| 4mb58 |
var countSort = function(arr, min, max) {
var i, z = 0, count = [];
for (i = min; i <= max; i++) {
count[i] = 0;
}
for (i=0; i < arr.length; i++) {
count[arr[i]]++;
}
for (i = min; i <= max; i++) {
while (count[i]-- > 0) {
arr[z++] = i;
}
}
} | 237Sorting algorithms/Counting sort
| 10javascript
| qknx8 |
use strict;
use warnings;
for my $test ( split /^(?=
{
my ( $id, $outline ) = $test =~ /(\V*?\n)(.*)/s;
my $sorted = validateandsort( $outline, $id =~ /descend/ );
print $test, '=' x 20, " answer:\n$sorted\n";
}
sub validateandsort
{
my ($outline, $descend) = @_;
$outline =~ /^\h*(?: \t|\t )/m and
return "ERROR: mixed tab and space indentaion\n";
my $adjust = 0;
$adjust++ while $outline =~ s/^(\h*)\H.*\n\1\K\h(?=\H)//m
or $outline =~ s/^(\h*)(\h)\H.*\n\1\K(?=\H)/$2/m;
$adjust and print "WARNING: adjusting indentation on some lines\n";
return levelsort($outline, $descend);
}
sub levelsort
{
my ($section, $descend) = @_;
my @parts;
while( $section =~ / ((\h*) .*\n) ( (?:\2\h.*\n)* )/gx )
{
my ($head, $rest) = ($1, $3);
push @parts, $head . ( $rest and levelsort($rest, $descend) );
}
join '', $descend ? reverse sort @parts : sort @parts;
}
__DATA__
zeta
beta
gamma
lambda
kappa
mu
delta
alpha
theta
iota
epsilon
zeta
beta
gamma
lambda
kappa
mu
delta
alpha
theta
iota
epsilon
alpha
epsilon
iota
theta
zeta
beta
delta
gamma
kappa
lambda
mu
zeta
beta
gamma
lambda
kappa
mu
delta
alpha
theta
iota
epsilon | 241Sort an outline at every level
| 2perl
| j2k7f |
shuffle = function(v) {
for(var j, x, i = v.length; i; j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
};
isSorted = function(v){
for(var i=1; i<v.length; i++) {
if (v[i-1] > v[i]) { return false; }
}
return true;
}
bogosort = function(v){
var sorted = false;
while(sorted == false){
v = shuffle(v);
sorted = isSorted(v);
}
return v;
} | 236Sorting algorithms/Bogosort
| 10javascript
| hvwjh |
int main()
{
char values[MAX][100],tempStr[100];
int i,j,isString=0;
double val[MAX],temp;
for(i=0;i<MAX;i++){
printf(,i+1,(i==0)?:((i==1)?:));
fgets(values[i],100,stdin);
for(j=0;values[i][j]!=00;j++){
if(((values[i][j]<'0' || values[i][j]>'9') && (values[i][j]!='.' ||values[i][j]!='-'||values[i][j]!='+'))
||((values[i][j]=='.' ||values[i][j]=='-'||values[i][j]=='+')&&(values[i][j+1]<'0' || values[i][j+1]>'9')))
isString = 1;
}
}
if(isString==0){
for(i=0;i<MAX;i++)
val[i] = atof(values[i]);
}
for(i=0;i<MAX-1;i++){
for(j=i+1;j<MAX;j++){
if(isString==0 && val[i]>val[j]){
temp = val[j];
val[j] = val[i];
val[i] = temp;
}
else if(values[i][0]>values[j][0]){
strcpy(tempStr,values[j]);
strcpy(values[j],values[i]);
strcpy(values[i],tempStr);
}
}
}
for(i=0;i<MAX;i++)
isString==1?printf(,'X'+i,values[i]):printf(,'X'+i,val[i]);
return 0;
} | 242Sort three variables
| 5c
| 5y4uk |
int mycmp(const void *s1, const void *s2)
{
const char *l = *(const char **)s1, *r = *(const char **)s2;
size_t ll = strlen(l), lr = strlen(r);
if (ll > lr) return -1;
if (ll < lr) return 1;
return strcasecmp(l, r);
}
int main()
{
const char *strings[] = {
, , , , , , , };
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
} | 243Sort using a custom comparator
| 5c
| qkqxc |
null | 236Sorting algorithms/Bogosort
| 11kotlin
| ltrcp |
null | 237Sorting algorithms/Counting sort
| 11kotlin
| j2a7r |
int compareStrings(const void *a, const void *b) {
const char **aa = (const char **)a;
const char **bb = (const char **)b;
return strcmp(*aa, *bb);
}
void lexOrder(int n, int *ints) {
char **strs;
int i, first = 1, last = n, k = n, len;
if (n < 1) {
first = n; last = 1; k = 2 - n;
}
strs = malloc(k * sizeof(char *));
for (i = first; i <= last; ++i) {
if (i >= 1) len = (int)log10(i) + 2;
else if (i == 0) len = 2;
else len = (int)log10(-i) + 3;
strs[i-first] = malloc(len);
sprintf(strs[i-first], , i);
}
qsort(strs, k, sizeof(char *), compareStrings);
for (i = 0; i < k; ++i) {
ints[i] = atoi(strs[i]);
free(strs[i]);
}
free(strs);
}
int main() {
int i, j, k, n, *ints;
int numbers[5] = {0, 5, 13, 21, -22};
printf();
for (i = 0; i < 5; ++i) {
k = n = numbers[i];
if (k < 1) k = 2 - k;
ints = malloc(k * sizeof(int));
lexOrder(n, ints);
printf(, n);
for (j = 0; j < k; ++j) {
printf(, ints[j]);
}
printf();
free(ints);
}
return 0;
} | 244Sort numbers lexicographically
| 5c
| 30tza |
'''Sort an outline at every level'''
from itertools import chain, product, takewhile, tee
from functools import cmp_to_key, reduce
def sortedOutline(cmp):
'''Either a message reporting inconsistent
indentation, or an outline sorted at every
level by the supplied comparator function.
'''
def go(outlineText):
indentTuples = indentTextPairs(
outlineText.splitlines()
)
return bindLR(
minimumIndent(enumerate(indentTuples))
)(lambda unitIndent: Right(
outlineFromForest(
unitIndent,
nest(foldTree(
lambda x: lambda xs: Node(x)(
sorted(xs, key=cmp_to_key(cmp))
)
)(Node('')(
forestFromIndentLevels(
indentLevelsFromLines(
unitIndent
)(indentTuples)
)
)))
)
))
return go
def main():
'''Ascending and descending sorts attempted on
space-indented and tab-indented outlines, both
well-formed and ill-formed.
'''
ascending = comparing(root)
descending = flip(ascending)
spacedOutline = '''
zeta
beta
gamma
lambda
kappa
mu
delta
alpha
theta
iota
epsilon'''
tabbedOutline = '''
zeta
beta
gamma
lambda
kappa
mu
delta
alpha
theta
iota
epsilon'''
confusedOutline = '''
alpha
epsilon
iota
theta
zeta
beta
delta
gamma
kappa
lambda
mu'''
raggedOutline = '''
zeta
beta
gamma
lambda
kappa
mu
delta
alpha
theta
iota
epsilon'''
def displaySort(kcmp):
'''Sort function output with labelled comparator
for a set of four labelled outlines.
'''
k, cmp = kcmp
return [
tested(cmp, k, label)(
outline
) for (label, outline) in [
('4-space indented', spacedOutline),
('tab indented', tabbedOutline),
('Unknown 1', confusedOutline),
('Unknown 2', raggedOutline)
]
]
def tested(cmp, cmpName, outlineName):
'''Print either message or result.
'''
def go(outline):
print('\n' + outlineName, cmpName + ':')
either(print)(print)(
sortedOutline(cmp)(outline)
)
return go
ap([
displaySort
])([
(, ascending),
(, descending)
])
def forestFromIndentLevels(tuples):
'''A list of trees derived from a list of values paired
with integers giving their levels of indentation.
'''
def go(xs):
if xs:
intIndent, v = xs[0]
firstTreeLines, rest = span(
lambda x: intIndent < x[0]
)(xs[1:])
return [Node(v)(go(firstTreeLines))] + go(rest)
else:
return []
return go(tuples)
def indentLevelsFromLines(indentUnit):
'''Each input line stripped of leading
white space, and tupled with a preceding integer
giving its level of indentation from 0 upwards.
'''
def go(xs):
w = len(indentUnit)
return [
(len(x[0])
for x in xs
]
return go
def indentTextPairs(xs):
'''A list of (indent, bodyText) pairs.'''
def indentAndText(s):
pfx = list(takewhile(lambda c: c.isspace(), s))
return (pfx, s[len(pfx):])
return [indentAndText(x) for x in xs]
def outlineFromForest(tabString, forest):
'''An indented outline serialisation of forest,
using tabString as the unit of indentation.
'''
def go(indent):
def serial(node):
return [indent + root(node)] + list(
concatMap(
go(tabString + indent)
)(nest(node))
)
return serial
return '\n'.join(
concatMap(go(''))(forest)
)
def minimumIndent(indexedPrefixes):
'''Either a message, if indentation characters are
mixed, or indentation widths are inconsistent,
or the smallest consistent non-empty indentation.
'''
(xs, ts) = tee(indexedPrefixes)
(ys, zs) = tee(ts)
def mindentLR(charSet):
if list(charSet):
def w(x):
return len(x[1][0])
unit = min(filter(w, ys), key=w)[1][0]
unitWidth = len(unit)
def widthCheck(a, ix):
'''Is there a line number at which
an anomalous indent width is seen?
'''
wx = len(ix[1][0])
return a if (a or 0 == wx) else (
ix[0] if 0 != wx% unitWidth else a
)
oddLine = reduce(widthCheck, zs, None)
return Left(
'Inconsistent indentation width at line ' + (
str(1 + oddLine)
)
) if oddLine else Right(''.join(unit))
else:
return Right('')
def tabSpaceCheck(a, ics):
'''Is there a line number at which a
variant indent character is used?
'''
charSet = a[0].union(set(ics[1][0]))
return a if a[1] else (
charSet, ics[0] if 1 < len(charSet) else None
)
indentCharSet, mbAnomalyLine = reduce(
tabSpaceCheck, xs, (set([]), None)
)
return bindLR(
Left(
'Mixed indent characters found in line ' + str(
1 + mbAnomalyLine
)
) if mbAnomalyLine else Right(list(indentCharSet))
)(mindentLR)
def Left(x):
'''Constructor for an empty Either (option type) value
with an associated string.
'''
return {'type': 'Either', 'Right': None, 'Left': x}
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
def Node(v):
'''Constructor for a Tree node which connects a
value of some kind to a list of zero or
more child trees.
'''
return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}
def ap(fs):
'''The application of each of a list of functions,
to each of a list of values.
'''
def go(xs):
return [
f(x) for (f, x)
in product(fs, xs)
]
return go
def bindLR(m):
'''Either monad injection operator.
Two computations sequentially composed,
with any value produced by the first
passed as an argument to the second.
'''
def go(mf):
return (
mf(m.get('Right')) if None is m.get('Left') else m
)
return go
def comparing(f):
'''An ordering function based on
a property accessor f.
'''
def go(x, y):
fx = f(x)
fy = f(y)
return -1 if fx < fy else (1 if fx > fy else 0)
return go
def concatMap(f):
'''A concatenated list over which a function has been mapped.
The list monad can be derived by using a function f which
wraps its output in a list,
(using an empty list to represent computational failure).
'''
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def either(fl):
'''The application of fl to e if e is a Left value,
or the application of fr to e if e is a Right value.
'''
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
) else fr(e['Right'])
def flip(f):
'''The binary function f with its
arguments reversed.
'''
return lambda a, b: f(b, a)
def foldTree(f):
'''The catamorphism on trees. A summary
value defined by a depth-first fold.
'''
def go(node):
return f(root(node))([
go(x) for x in nest(node)
])
return go
def nest(t):
'''Accessor function for children of tree node.'''
return t.get('nest')
def root(t):
'''Accessor function for data of tree node.'''
return t.get('root')
def span(p):
'''The longest (possibly empty) prefix of xs
that contains only elements satisfying p,
tupled with the remainder of xs.
span p xs is equivalent to
(takeWhile p xs, dropWhile p xs).
'''
def match(ab):
b = ab[1]
return not b or not p(b[0])
def f(ab):
a, b = ab
return a + [b[0]], b[1:]
def go(xs):
return until(match)(f)(([], xs))
return go
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
if __name__ == '__main__':
main() | 241Sort an outline at every level
| 3python
| hvbjw |
function bogosort (list)
if type (list) ~= 'table' then return list end | 236Sorting algorithms/Bogosort
| 1lua
| 2z7l3 |
package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() { | 239Sorting algorithms/Bead sort
| 0go
| e7sa6 |
function CountingSort( f )
local min, max = math.min( unpack(f) ), math.max( unpack(f) )
local count = {}
for i = min, max do
count[i] = 0
end
for i = 1, #f do
count[ f[i] ] = count[ f[i] ] + 1
end
local z = 1
for i = min, max do
while count[i] > 0 do
f[z] = i
z = z + 1
count[i] = count[i] - 1
end
end
end
f = { 15, -3, 0, -1, 5, 4, 5, 20, -8 }
CountingSort( f )
for i in next, f do
print( f[i] )
end | 237Sorting algorithms/Counting sort
| 1lua
| hvej8 |
def beadSort = { list ->
final nPoles = list.max()
list.collect {
print "."
([true] * it) + ([false] * (nPoles - it))
}.transpose().collect { pole ->
print "."
pole.findAll { ! it } + pole.findAll { it }
}.transpose().collect{ beadTally ->
beadTally.findAll{ it }.size()
}
} | 239Sorting algorithms/Bead sort
| 7groovy
| kuah7 |
(def n 13)
(sort-by str (range 1 (inc n))) | 244Sort numbers lexicographically
| 6clojure
| cdm9b |
import Data.List
beadSort :: [Int] -> [Int]
beadSort = map sum. transpose. transpose. map (flip replicate 1) | 239Sorting algorithms/Bead sort
| 8haskell
| 389zj |
(defn rosetta-compare [s1 s2]
(let [len1 (count s1), len2 (count s2)]
(if (= len1 len2)
(compare (.toLowerCase s1) (.toLowerCase s2))
(- len2 len1))))
(println
(sort rosetta-compare
["Here" "are" "some" "sample" "strings" "to" "be" "sorted"])) | 243Sort using a custom comparator
| 6clojure
| ieiom |
public class BeadSort
{
public static void main(String[] args)
{
BeadSort now=new BeadSort();
int[] arr=new int[(int)(Math.random()*11)+5];
for(int i=0;i<arr.length;i++)
arr[i]=(int)(Math.random()*10);
System.out.print("Unsorted: ");
now.display1D(arr);
int[] sort=now.beadSort(arr);
System.out.print("Sorted: ");
now.display1D(sort);
}
int[] beadSort(int[] arr)
{
int max=a[0];
for(int i=1;i<arr.length;i++)
if(arr[i]>max)
max=arr[i]; | 239Sorting algorithms/Bead sort
| 9java
| ietos |
cities = [ {, },
{, },
{, },
{, } ]
IO.inspect Enum.sort(cities)
IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end)
IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end)
IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end) | 245Sort stability
| 5c
| r95g7 |
package main
import (
"fmt"
"sort"
"strconv"
)
func lexOrder(n int) []int {
first, last, k := 1, n, n
if n < 1 {
first, last, k = n, 1, 2-n
}
strs := make([]string, k)
for i := first; i <= last; i++ {
strs[i-first] = strconv.Itoa(i)
}
sort.Strings(strs)
ints := make([]int, k)
for i := 0; i < k; i++ {
ints[i], _ = strconv.Atoi(strs[i])
}
return ints
}
func main() {
fmt.Println("In lexicographical order:\n")
for _, n := range []int{0, 5, 13, 21, -22} {
fmt.Printf("%3d:%v\n", n, lexOrder(n))
}
} | 244Sort numbers lexicographically
| 0go
| buhkh |
$ function bubble_sort() {
local a=("$@")
local n
local i
local j
local t
ft=(false true)
n=${
i=n
while ${ft[$(( 0 < i ))]}
do
j=0
while ${ft[$(( j+1 < i ))]}
do
if ${ft[$(( a[j+1] < a[j] ))]}
then
t=${a[j+1]}
a[j+1]=${a[j]}
a[j]=$t
fi
t=$(( ++j ))
done
t=$(( --i ))
done
echo ${a[@]}
}
> > > > > > > > > > > > > > > > > > > > > > > > > $
$ bubble_sort 3 2 8
2 3 8
$
$ a=(2 45 83 89 1 82 69 88 112 99 0 82 58 65 782 74 -31 104 4 2)
$ bubble_sort ${a[@]}
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
$ b=($( bubble_sort ${a[@]} ) )
$ echo ${
20
$ echo ${b[@]}
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
$ | 246Sorting algorithms/Bubble sort
| 4bash
| skeql |
cities = [ {"UK", "London"},
{"US", "New York"},
{"US", "Birmingham"},
{"UK", "Birmingham"} ]
IO.inspect Enum.sort(cities)
IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end)
IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end)
IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end) | 245Sort stability
| 6clojure
| bujkz |
import Data.List (sort)
task :: (Ord b, Show b) => [b] -> [b]
task = map snd . sort . map (\i -> (show i, i))
main = print $ task [1 .. 13] | 244Sort numbers lexicographically
| 8haskell
| dwin4 |
package main
import "fmt"
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
gnomeSort(a)
fmt.Println("after: ", a)
}
func gnomeSort(a []int) {
for i, j := 1, 2; i < len(a); {
if a[i-1] > a[i] {
a[i-1], a[i] = a[i], a[i-1]
i--
if i > 0 {
continue
}
}
i = j
j++
}
} | 238Sorting algorithms/Gnome sort
| 0go
| sbnqa |
null | 239Sorting algorithms/Bead sort
| 11kotlin
| qkox1 |
import java.util.List;
import java.util.stream.*;
public class LexicographicalNumbers {
static List<Integer> lexOrder(int n) {
int first = 1, last = n;
if (n < 1) {
first = n;
last = 1;
}
return IntStream.rangeClosed(first, last)
.mapToObj(Integer::toString)
.sorted()
.map(Integer::valueOf)
.collect(Collectors.toList());
}
public static void main(String[] args) {
System.out.println("In lexicographical order:\n");
int[] ints = {0, 5, 13, 21, -22};
for (int n : ints) {
System.out.printf("%3d:%s\n", n, lexOrder(n));
}
}
} | 244Sort numbers lexicographically
| 9java
| skxq0 |
sub combSort {
my @arr = @_;
my $gap = @arr;
my $swaps = 1;
while ($gap > 1 || $swaps) {
$gap /= 1.25 if $gap > 1;
$swaps = 0;
foreach my $i (0 .. $
if ($arr[$i] > $arr[$i+$gap]) {
@arr[$i, $i+$gap] = @arr[$i+$gap, $i];
$swaps = 1;
}
}
}
return @arr;
} | 235Sorting algorithms/Comb sort
| 2perl
| p40b0 |
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 gnomeSort = { input ->
def swap = checkSwap.curry(input)
def index = 1
while (index < input.size()) {
index += (swap(index-1) && index > 1) ? -1: 1
}
input
} | 238Sorting algorithms/Gnome sort
| 7groovy
| ars1p |
null | 239Sorting algorithms/Bead sort
| 1lua
| sbiq8 |
void bubble_sort (int *a, int n) {
int i, t, j = n, s = 1;
while (s) {
s = 0;
for (i = 1; i < j; i++) {
if (a[i] < a[i - 1]) {
t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
s = 1;
}
}
j--;
}
}
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 ? : );
bubble_sort(a, n);
for (i = 0; i < n; i++)
printf(, a[i], i == n - 1 ? : );
return 0;
} | 246Sorting algorithms/Bubble sort
| 5c
| 8px04 |
gnomeSort [] = []
gnomeSort (x:xs) = gs [x] xs
where
gs vv@(v:vs) (w:ws)
| v<=w = gs (w:vv) ws
| otherwise = gs vs (w:v:ws)
gs [] (y:ys) = gs [y] ys
gs xs [] = reverse xs | 238Sorting algorithms/Gnome sort
| 8haskell
| 9dumo |
null | 244Sort numbers lexicographically
| 11kotlin
| agp13 |
function combSort($arr){
$gap = count($arr);
$swap = true;
while ($gap > 1 || $swap){
if($gap > 1) $gap /= 1.25;
$swap = false;
$i = 0;
while($i+$gap < count($arr)){
if($arr[$i] > $arr[$i+$gap]){
list($arr[$i], $arr[$i+$gap]) = array($arr[$i+$gap],$arr[$i]);
$swap = true;
}
$i++;
}
}
return $arr;
} | 235Sorting algorithms/Comb sort
| 12php
| yi561 |
def cityList = ['UK London', 'US New York', 'US Birmingham', 'UK Birmingham',].asImmutable()
[
'Sort by city': { city -> city[4..-1] },
'Sort by country': { city -> city[0..3] },
].each{ String label, Closure orderBy ->
println "\n\nBefore ${label}"
cityList.each { println it }
println "\nAfter ${label}"
cityList.sort(false, orderBy).each{ println it }
} | 245Sort stability
| 0go
| ne8i1 |
def cityList = ['UK London', 'US New York', 'US Birmingham', 'UK Birmingham',].asImmutable()
[
'Sort by city': { city -> city[4..-1] },
'Sort by country': { city -> city[0..3] },
].each{ String label, Closure orderBy ->
println "\n\nBefore ${label}"
cityList.each { println it }
println "\nAfter ${label}"
cityList.sort(false, orderBy).each{ println it }
} | 245Sort stability
| 7groovy
| skwq1 |
function lexNums (limit)
local numbers = {}
for i = 1, limit do
table.insert(numbers, tostring(i))
end
table.sort(numbers)
return numbers
end
local numList = lexNums(13)
print(table.concat(numList, " ")) | 244Sort numbers lexicographically
| 1lua
| er1ac |
package main
import "fmt"
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
cocktailSort(a)
fmt.Println("after: ", a)
}
func cocktailSort(a []int) {
last := len(a) - 1
for {
swapped := false
for i := 0; i < last; i++ {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
swapped = false
for i := last - 1; i >= 0; i-- {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
}
} | 240Sorting algorithms/Cocktail sort
| 0go
| arx1f |
import java.util.Arrays;
import java.util.Comparator;
public class RJSortStability {
public static void main(String[] args) {
String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", };
String[] cn = cityList.clone();
System.out.println("\nBefore sort:");
for (String city : cn) {
System.out.println(city);
}
// sort by city
Arrays.sort(cn, new Comparator<String>() {
public int compare(String lft, String rgt) {
return lft.substring(4).compareTo(rgt.substring(4));
}
});
System.out.println("\nAfter sort on city:");
for (String city : cn) {
System.out.println(city);
}
cn = cityList.clone();
System.out.println("\nBefore sort:");
for (String city : cn) {
System.out.println(city);
}
// sort by country
Arrays.sort(cn, new Comparator<String>() {
public int compare(String lft, String rgt) {
return lft.substring(0, 2).compareTo(rgt.substring(0, 2));
}
});
System.out.println("\nAfter sort on country:");
for (String city : cn) {
System.out.println(city);
}
System.out.println();
}
} | 245Sort stability
| 8haskell
| u3lv2 |
package main
import (
"fmt"
"log"
"sort"
)
var (
stringsIn = []string{
`lions, tigers, and`,
`bears, oh my!`,
`(from the "Wizard of OZ")`}
intsIn = []int{77444, -12, 0}
)
func main() {
{ | 242Sort three variables
| 0go
| 81o0g |
(ns bubblesort
(:import java.util.ArrayList))
(defn bubble-sort
"Sort in-place.
arr must implement the Java List interface and should support
random access, e.g. an ArrayList."
([arr] (bubble-sort compare arr))
([cmp arr]
(letfn [(swap! [i j]
(let [t (.get arr i)]
(doto arr
(.set i (.get arr j))
(.set j t))))
(sorter [stop-i]
(let [changed (atom false)]
(doseq [i (range stop-i)]
(if (pos? (cmp (.get arr i) (.get arr (inc i))))
(do
(swap! i (inc i))
(reset! changed true))))
@changed))]
(doseq [stop-i (range (dec (.size arr)) -1 -1)
:while (sorter stop-i)])
arr)))
(println (bubble-sort (ArrayList. [10 9 8 7 6 5 4 3 2 1]))) | 246Sorting algorithms/Bubble sort
| 6clojure
| fxodm |
def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find{ it }.each { makeSwap(a, i, j) } }
def cocktailSort = { list ->
if (list == null || list.size() < 2) return list
def n = list.size()
def swap = checkSwap.curry(list)
while (true) {
def swapped = (0..(n-2)).any(swap) && ((-2)..(-n)).any(swap)
if ( ! swapped ) break
}
list
} | 240Sorting algorithms/Cocktail sort
| 7groovy
| hvpj9 |
printf("%4d: [%s]\n", $_, join ',', sort $_ > 0 ? 1..$_ : $_..1) for 13, 21, -22 | 244Sort numbers lexicographically
| 2perl
| 9nymn |
import Data.List (sort)
sortedTriple
:: Ord a
=> (a, a, a) -> (a, a, a)
sortedTriple (x, y, z) =
let [a, b, c] = sort [x, y, z]
in (a, b, c)
sortedListfromTriple
:: Ord a
=> (a, a, a) -> [a]
sortedListfromTriple (x, y, z) = sort [x, y, z]
main :: IO ()
main = do
print $
sortedTriple
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
print $
sortedListfromTriple
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
print $ sortedTriple (77444, -12, 0)
print $ sortedListfromTriple (77444, -12, 0) | 242Sort three variables
| 8haskell
| lt2ch |
cocktailSort :: Ord a => [a] -> [a]
cocktailSort l
| not swapped1 = l
| not swapped2 = reverse $ l1
| otherwise = cocktailSort l2
where (swapped1, l1) = swappingPass (>) (False, []) l
(swapped2, l2) = swappingPass (<) (False, []) l1
swappingPass :: Ord a => (a -> a -> Bool) -> (Bool, [a]) -> [a] -> (Bool, [a])
swappingPass op (swapped, l) (x1: x2: xs)
| op x1 x2 = swappingPass op (True, x2: l) (x1: xs)
| otherwise = swappingPass op (swapped, x1: l) (x2: xs)
swappingPass _ (swapped, l) [x] = (swapped, x: l)
swappingPass _ pair [] = pair | 240Sorting algorithms/Cocktail sort
| 8haskell
| z0yt0 |
void bubble_sort(int *idx, int n_idx, int *buf)
{
int i, j, tmp;
for_ij { sort(idx[j], idx[i]); }
for_ij { sort(buf[idx[j]], buf[idx[i]]);}
}
int main()
{
int values[] = {7, 6, 5, 4, 3, 2, 1, 0};
int idx[] = {6, 1, 7};
int i;
printf();
for (i = 0; i < 8; i++)
printf(, values[i]);
printf();
bubble_sort(idx, 3, values);
for (i = 0; i < 8; i++)
printf(, values[i]);
printf();
return 0;
} | 247Sort disjoint sublist
| 5c
| skaq5 |
use strict;
sub counting_sort
{
my ($a, $min, $max) = @_;
my @cnt = (0) x ($max - $min + 1);
$cnt[$_ - $min]++ foreach @$a;
my $i = $min;
@$a = map {($i++) x $_} @cnt;
} | 237Sorting algorithms/Counting sort
| 2perl
| ts9fg |
import java.util.Arrays;
import java.util.Comparator;
public class RJSortStability {
public static void main(String[] args) {
String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", };
String[] cn = cityList.clone();
System.out.println("\nBefore sort:");
for (String city : cn) {
System.out.println(city);
} | 245Sort stability
| 9java
| mi3ym |
import java.util.Comparator;
import java.util.stream.Stream;
class Box {
public int weightKg;
Box(final int weightKg) {
this.weightKg = weightKg;
}
}
public class Sort3Vars {
public static void main(String... args) {
int iA = 21;
int iB = 11;
int iC = 82;
int[] sortedInt = Stream.of(iA, iB, iC).sorted().mapToInt(Integer::intValue).toArray();
iA = sortedInt[0];
iB = sortedInt[1];
iC = sortedInt[2];
System.out.printf("Sorted values:%d%d%d%n", iA, iB, iC);
String sA = "s21";
String sB = "s11";
String sC = "s82";
Object[] sortedStr = Stream.of(sA, sB, sC).sorted().toArray();
sA = (String) sortedStr[0];
sB = (String) sortedStr[1];
sC = (String) sortedStr[2];
System.out.printf("Sorted values:%s%s%s%n", sA, sB, sC);
Box bA = new Box(200);
Box bB = new Box(12);
Box bC = new Box(143); | 242Sort three variables
| 9java
| 386zg |
>>> def combsort(input):
gap = len(input)
swaps = True
while gap > 1 or swaps:
gap = max(1, int(gap / 1.25))
swaps = False
for i in range(len(input) - gap):
j = i+gap
if input[i] > input[j]:
input[i], input[j] = input[j], input[i]
swaps = True
>>> y = [88, 18, 31, 44, 4, 0, 8, 81, 14, 78, 20, 76, 84, 33, 73, 75, 82, 5, 62, 70]
>>> combsort(y)
>>> assert y == sorted(y)
>>> y
[0, 4, 5, 8, 14, 18, 20, 31, 33, 44, 62, 70, 73, 75, 76, 78, 81, 82, 84, 88]
>>> | 235Sorting algorithms/Comb sort
| 3python
| 1g8pc |
public static void gnomeSort(int[] a)
{
int i=1;
int j=2;
while(i < a.length) {
if ( a[i-1] <= a[i] ) {
i = j; j++;
} else {
int tmp = a[i-1];
a[i-1] = a[i];
a[i--] = tmp;
i = (i==0) ? j++ : i;
}
}
} | 238Sorting algorithms/Gnome sort
| 9java
| tsmf9 |
sub beadsort {
my @data = @_;
my @columns;
my @rows;
for my $datum (@data) {
for my $column ( 0 .. $datum-1 ) {
++ $rows[ $columns[$column]++ ];
}
}
return reverse @rows;
}
beadsort 5, 7, 1, 3, 1, 1, 20; | 239Sorting algorithms/Bead sort
| 2perl
| v3g20 |
ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]]
print(ary);
ary.sort(function(a,b){return (a[1]<b[1] ? -1 : (a[1]>b[1] ? 1 : 0))});
print(ary); | 245Sort stability
| 10javascript
| vzc25 |
n=13
print(sorted(range(1,n+1), key=str)) | 244Sort numbers lexicographically
| 3python
| cdm9q |
const printThree = (note, [a, b, c], [a1, b1, c1]) => {
console.log(`${note}
${a} is: ${a1}
${b} is: ${b1}
${c} is: ${c1}
`);
};
const sortThree = () => {
let a = 'lions, tigers, and';
let b = 'bears, oh my!';
let c = '(from the "Wizard of OZ")';
printThree('Before Sorting', ['a', 'b', 'c'], [a, b, c]);
[a, b, c] = [a, b, c].sort();
printThree('After Sorting', ['a', 'b', 'c'], [a, b, c]);
let x = 77444;
let y = -12;
let z = 0;
printThree('Before Sorting', ['x', 'y', 'z'], [x, y, z]);
[x, y, z] = [x, y, z].sort();
printThree('After Sorting', ['x', 'y', 'z'], [x, y, z]);
};
sortThree(); | 242Sort three variables
| 10javascript
| cfl9j |
comb.sort<-function(a){
gap<-length(a)
swaps<-1
while(gap>1 & swaps==1){
gap=floor(gap/1.3)
if(gap<1){
gap=1
}
swaps=0
i=1
while(i+gap<=length(a)){
if(a[i]>a[i+gap]){
a[c(i,i+gap)] <- a[c(i+gap,i)]
swaps=1
}
i<-i+1
}
}
return(a)
} | 235Sorting algorithms/Comb sort
| 13r
| hvxjj |
use List::Util qw(shuffle);
sub bogosort
{my @l = @_;
@l = shuffle(@l) until in_order(@l);
return @l;}
sub in_order
{my $last = shift;
foreach (@_)
{$_ >= $last or return 0;
$last = $_;}
return 1;} | 236Sorting algorithms/Bogosort
| 2perl
| qkdx6 |
function gnomeSort(a) {
function moveBack(i) {
for( ; i > 0 && a[i-1] > a[i]; i--) {
var t = a[i];
a[i] = a[i-1];
a[i-1] = t;
}
}
for (var i = 1; i < a.length; i++) {
if (a[i-1] > a[i]) moveBack(i);
}
return a;
} | 238Sorting algorithms/Gnome sort
| 10javascript
| mnvyv |
<?php
function counting_sort(&$arr, $min, $max)
{
$count = array();
for($i = $min; $i <= $max; $i++)
{
$count[$i] = 0;
}
foreach($arr as $number)
{
$count[$number]++;
}
$z = 0;
for($i = $min; $i <= $max; $i++) {
while( $count[$i]-- > 0 ) {
$arr[$z++] = $i;
}
}
} | 237Sorting algorithms/Counting sort
| 12php
| kuwhv |
(defn disjoint-sort [coll idxs]
(let [val-subset (keep-indexed #(when ((set idxs) %) %2) coll)
replacements (zipmap (set idxs) (sort val-subset))]
(apply assoc coll (flatten (seq replacements))))) | 247Sort disjoint sublist
| 6clojure
| nesik |
null | 245Sort stability
| 11kotlin
| tqnf0 |
<?php
function columns($arr) {
if (count($arr) == 0)
return array();
else if (count($arr) == 1)
return array_chunk($arr[0], 1);
array_unshift($arr, NULL);
$transpose = call_user_func_array('array_map', $arr);
return array_map('array_filter', $transpose);
}
function beadsort($arr) {
foreach ($arr as $e)
$poles []= array_fill(0, $e, 1);
return array_map('count', columns(columns($poles)));
}
print_r(beadsort(array(5,3,1,7,4,1,1)));
?> | 239Sorting algorithms/Bead sort
| 12php
| 0pnsp |
typedef struct oid_tag {
char* str_;
int* numbers_;
int length_;
} oid;
void oid_destroy(oid* p) {
if (p != 0) {
free(p->str_);
free(p->numbers_);
free(p);
}
}
int char_count(const char* str, char ch) {
int count = 0;
for (const char* p = str; *p; ++p) {
if (*p == ch)
++count;
}
return count;
}
oid* oid_create(const char* str) {
oid* ptr = calloc(1, sizeof(oid));
if (ptr == 0)
return 0;
ptr->str_ = strdup(str);
if (ptr->str_ == 0) {
oid_destroy(ptr);
return 0;
}
int dots = char_count(str, '.');
ptr->numbers_ = malloc(sizeof(int) * (dots + 1));
if (ptr->numbers_ == 0) {
oid_destroy(ptr);
return 0;
}
ptr->length_ = dots + 1;
const char* p = str;
for (int i = 0; i <= dots && *p;) {
char* eptr = 0;
int num = strtol(p, &eptr, 10);
if (*eptr != 0 && *eptr != '.') {
oid_destroy(ptr);
return 0;
}
ptr->numbers_[i++] = num;
p = eptr;
if (*p)
++p;
}
return ptr;
}
int oid_compare(const void* p1, const void* p2) {
const oid* o1 = *(oid* const*)p1;
const oid* o2 = *(oid* const*)p2;
int i1 = 0, i2 = 0;
for (; i1 < o1->length_ && i2 < o2->length_; ++i1, ++i2) {
if (o1->numbers_[i1] < o2->numbers_[i2])
return -1;
if (o1->numbers_[i1] > o2->numbers_[i2])
return 1;
}
if (o1->length_ < o2->length_)
return -1;
if (o1->length_ > o2->length_)
return 1;
return 0;
}
int main() {
const char* input[] = {
,
,
,
,
,
};
const int len = sizeof(input)/sizeof(input[0]);
oid* oids[len];
memset(oids, 0, sizeof(oids));
int i;
for (i = 0; i < len; ++i) {
oids[i] = oid_create(input[i]);
if (oids[i] == 0)
{
fprintf(stderr, );
goto cleanup;
}
}
qsort(oids, len, sizeof(oid*), oid_compare);
for (i = 0; i < len; ++i)
puts(oids[i]->str_);
cleanup:
for (i = 0; i < len; ++i)
oid_destroy(oids[i]);
return 0;
} | 248Sort a list of object identifiers
| 5c
| o1w80 |
n = 13
p (1..n).sort_by(&:to_s) | 244Sort numbers lexicographically
| 14ruby
| 2tclw |
fn lex_sorted_vector(num: i32) -> Vec<i32> {
let (min, max) = if num >= 1 { (1, num) } else { (num, 1) };
let mut str: Vec<String> = (min..=max).map(|i| i.to_string()).collect();
str.sort();
str.iter().map(|s| s.parse::<i32>().unwrap()).collect()
}
fn main() {
for n in &[0, 5, 13, 21, -22] {
println!("{}: {:?}", n, lex_sorted_vector(*n));
}
} | 244Sort numbers lexicographically
| 15rust
| vzl2t |
object LexicographicalNumbers extends App { def ints = List(0, 5, 13, 21, -22)
def lexOrder(n: Int): Seq[Int] = (if (n < 1) n to 1 else 1 to n).sortBy(_.toString)
println("In lexicographical order:\n")
for (n <- ints) println(f"$n%3d: ${lexOrder(n).mkString("[",", ", "]")}%s")
} | 244Sort numbers lexicographically
| 16scala
| 4yu50 |
null | 242Sort three variables
| 11kotlin
| nwdij |
function bogosort($l) {
while (!in_order($l))
shuffle($l);
return $l;
}
function in_order($l) {
for ($i = 1; $i < count($l); $i++)
if ($l[$i] < $l[$i-1])
return FALSE;
return TRUE;
} | 236Sorting algorithms/Bogosort
| 12php
| v3j2v |
Module Stable {
Inventory queue alfa
Stack New {
Data "UK", "London","US", "New York","US", "Birmingham", "UK","Birmingham"
While not empty {
Append alfa, Letter$:=letter$
}
}
sort alfa
k=Each(alfa)
Document A$
NL$={
}
While k {
A$= Eval$(k, k^)+" "+eval$(k)+NL$
}
Clipboard A$ ' write to clipboard
Report A$
}
Call Stable
Output:
UK London
UK Birmingham
US New York
US Birmingham | 245Sort stability
| 1lua
| zsdty |
func lex(n: Int) -> [Int] {
return stride(from: 1, through: n, by: n.signum()).map({ String($0) }).sorted().compactMap(Int.init)
}
print("13: \(lex(n: 13))")
print("21: \(lex(n: 21))")
print("-22: \(lex(n: -22))") | 244Sort numbers lexicographically
| 17swift
| lf9c2 |
List<num> bubbleSort(List<num> list) {
var retList = new List<num>.from(list);
var tmp;
var swapped = false;
do {
swapped = false;
for(var i = 1; i < retList.length; i++) {
if(retList[i - 1] > retList[i]) {
tmp = retList[i - 1];
retList[i - 1] = retList[i];
retList[i] = tmp;
swapped = true;
}
}
} while(swapped);
return retList;
} | 246Sorting algorithms/Bubble sort
| 18dart
| erban |
null | 238Sorting algorithms/Gnome sort
| 11kotlin
| oat8z |
function variadicSort (...)
local t = {}
for _, x in pairs{...} do
table.insert(t, x)
end
table.sort(t)
return unpack(t)
end
local testCases = {
{ x = 'lions, tigers, and',
y = 'bears, oh my!',
z = '(from the "Wizard of OZ")'
},
{ x = 77444,
y = -12,
z = 0
}
}
for i, case in ipairs(testCases) do
x, y, z = variadicSort(case.x, case.y, case.z)
print("\nCase " .. i)
print("\tx = " .. x)
print("\ty = " .. y)
print("\tz = " .. z)
end | 242Sort three variables
| 1lua
| dxfnq |
package main
import (
"fmt"
"sort"
"strings"
)
type sortable []string
func (s sortable) Len() int { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
a, b := s[i], s[j]
if len(a) != len(b) {
return len(a) > len(b)
}
return strings.ToLower(a) < strings.ToLower(b)
}
func main() {
var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
fmt.Println(s, "(original)")
sort.Sort(s)
fmt.Println(s, "(sorted)")
} | 243Sort using a custom comparator
| 0go
| 2z2l7 |
function gnomeSort(a)
local i, j = 2, 3
while i <= #a do
if a[i-1] <= a[i] then
i = j
j = j + 1
else
a[i-1], a[i] = a[i], a[i-1] | 238Sorting algorithms/Gnome sort
| 1lua
| iezot |
public static void cocktailSort( int[] A ){
boolean swapped;
do {
swapped = false;
for (int i =0; i<= A.length - 2;i++) {
if (A[ i ] > A[ i + 1 ]) { | 240Sorting algorithms/Cocktail sort
| 9java
| oad8d |
>>> from collections import defaultdict
>>> def countingSort(array, mn, mx):
count = defaultdict(int)
for i in array:
count[i] += 1
result = []
for j in range(mn,mx+1):
result += [j]* count[j]
return result
>>> data = [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10, 2, 1, 3, 8, 7, 3, 9, 5, 8, 5, 1, 6, 3, 7, 5, 4, 6, 9, 9, 6, 6, 10, 2, 4, 5, 2, 8, 2, 2, 5, 2, 9, 3, 3, 5, 7, 8, 4]
>>> mini,maxi = 1,10
>>> countingSort(data, mini, maxi) == sorted(data)
True | 237Sorting algorithms/Counting sort
| 3python
| z0ctt |
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
} | 249Solve a Numbrix puzzle
| 0go
| yon64 |
(defn oid-vec [oid-str]
(->> (clojure.string/split oid-str #"\.")
(map #(Long. %))))
(defn oid-str [oid-vec]
(clojure.string/join "." oid-vec))
(defn oid-compare [a b]
(let [min-len (min (count a) (count b))
common-cmp (compare (vec (take min-len a))
(vec (take min-len b)))]
(if (zero? common-cmp)
(compare (count a) (count b))
common-cmp)))
(defn sort-oids [oid-strs]
(->> (map oid-vec oid-strs)
(sort oid-compare)
(map oid-str))) | 248Sort a list of object identifiers
| 6clojure
| tq8fv |
def strings = "Here are some sample strings to be sorted".split()
strings.sort { x, y ->
y.length() <=> x.length() ?: x.compareToIgnoreCase(y)
}
println strings | 243Sort using a custom comparator
| 7groovy
| yiy6o |
class Array
def combsort!
gap = size
swaps = true
while gap > 1 or swaps
gap = [1, (gap / 1.25).to_i].max
swaps = false
0.upto(size - gap - 1) do |i|
if self[i] > self[i+gap]
self[i], self[i+gap] = self[i+gap], self[i]
swaps = true
end
end
end
self
end
end
p [23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78].combsort! | 235Sorting algorithms/Comb sort
| 14ruby
| e7iax |
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1])) | 239Sorting algorithms/Bead sort
| 3python
| u6rvd |
null | 240Sorting algorithms/Cocktail sort
| 10javascript
| ts6fm |
counting_sort <- function(arr, minval, maxval) {
r <- arr
z <- 1
for(i in minval:maxval) {
cnt = sum(arr == i)
while(cnt > 0) {
r[z] = i
z <- z + 1
cnt <- cnt - 1
}
}
r
}
ages <- floor(runif(100, 0, 140+1))
sorted <- counting_sort(ages, 0, 140)
print(sorted) | 237Sorting algorithms/Counting sort
| 13r
| nw6i2 |
import Data.Char (toLower)
import Data.List (sortBy)
import Data.Ord (comparing)
lengthThenAZ :: String -> String -> Ordering
lengthThenAZ = comparing length <> comparing (fmap toLower)
descLengthThenAZ :: String -> String -> Ordering
descLengthThenAZ =
flip (comparing length)
<> comparing (fmap toLower)
main :: IO ()
main =
mapM_
putStrLn
( fmap
unlines
( [sortBy] <*> [lengthThenAZ, descLengthThenAZ]
<*> [ [ "Here",
"are",
"some",
"sample",
"strings",
"to",
"be",
"sorted"
]
]
)
) | 243Sort using a custom comparator
| 8haskell
| ara1g |
fn comb_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
let mut gap = len;
let mut swapped = true;
while gap > 1 || swapped {
gap = (4 * gap) / 5;
if gap < 1 {
gap = 1;
}
let mut i = 0;
swapped = false;
while i + gap < len {
if a[i] > a[i + gap] {
a.swap(i, i + gap);
swapped = true;
}
i += 1;
}
}
}
fn main() {
let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
println!("before: {:?}", v);
comb_sort(&mut v);
println!("after: {:?}", v);
} | 235Sorting algorithms/Comb sort
| 15rust
| wjne4 |
import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
} | 249Solve a Numbrix puzzle
| 9java
| 56muf |
use sort 'stable'; | 245Sort stability
| 2perl
| kv7hc |
import random
def bogosort(l):
while not in_order(l):
random.shuffle(l)
return l
def in_order(l):
if not l:
return True
last = l[0]
for x in l[1:]:
if x < last:
return False
last = x
return True | 236Sorting algorithms/Bogosort
| 3python
| sbfq9 |
package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
} | 250Solve a Hopido puzzle
| 0go
| h2vjq |
int connections[15][2] = {
{0, 2}, {0, 3}, {0, 4},
{1, 3}, {1, 4}, {1, 5},
{6, 2}, {6, 3}, {6, 4},
{7, 3}, {7, 4}, {7, 5},
{2, 3}, {3, 4}, {4, 5},
};
int pegs[8];
int num = 0;
bool valid() {
int i;
for (i = 0; i < 15; i++) {
if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) {
return false;
}
}
return true;
}
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
void printSolution() {
printf(, num++);
printf(, pegs[0], pegs[1]);
printf(, pegs[2], pegs[3], pegs[4], pegs[5]);
printf(, pegs[6], pegs[7]);
printf();
}
void solution(int le, int ri) {
if (le == ri) {
if (valid()) {
printSolution();
}
} else {
int i;
for (i = le; i <= ri; i++) {
swap(pegs + le, pegs + i);
solution(le + 1, ri);
swap(pegs + le, pegs + i);
}
}
}
int main() {
int i;
for (i = 0; i < 8; i++) {
pegs[i] = i + 1;
}
solution(0, 8 - 1);
return 0;
} | 251Solve the no connection puzzle
| 5c
| 2ttlo |
null | 249Solve a Numbrix puzzle
| 11kotlin
| cdt98 |
int intcmp(const void *aa, const void *bb)
{
const int *a = aa, *b = bb;
return (*a < *b) ? -1 : (*a > *b);
}
int main()
{
int nums[5] = {2,4,3,1,2};
qsort(nums, 5, sizeof(int), intcmp);
printf(,
nums[0], nums[1], nums[2], nums[3], nums[4]);
return 0;
} | 252Sort an integer array
| 5c
| p5uby |
package main
import (
"fmt"
"log"
"math/big"
"sort"
"strings"
)
var testCases = []string{
"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4.1.11.2.17.19.3.4.0.1",
"1.3.6.1.4.1.11150.3.4.0",
} | 248Sort a list of object identifiers
| 0go
| 4yc52 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.