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 (... | 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 +... | 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
r... | 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
... | 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
... | 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 = ... | 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]!='-'||val... | 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(st... | 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;
}... | 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.
'''
... | 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
... | 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 }.... | 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.prin... | 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... | 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]}
... | 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(citi... | 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--
... | 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)
.map... | 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;
... | 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... | 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--;
}
}
... | 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++;
}... | 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 ... | 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 ... | 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] > ... | 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 ... | 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)]
... | 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) ... | 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,... | 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]) ->... | 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 (... | 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 ... | 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[]... | 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]
... | 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... | 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($a... | 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... | 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] {
... | 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$={
... | 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... | 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 ipair... | 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)
... | 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... | 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... | 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... | 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
en... | 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)
ma... | 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 {
i... | 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... | 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,... | 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... | 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... | 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.