code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
library(proto) stack <- proto(expr = { l <- list() empty <- function(.) length(.$l) == 0 push <- function(., x) { .$l <- c(list(x), .$l) print(.$l) invisible() } pop <- function(.) { if(.$empty()) stop("can't pop from an empty list") .$l[[1]] <- NULL print(.$l) invisible() } }) stack$empty() stack$push(3) stack$push("abc") stack$push(matrix(1:6, nrow=2)) stack$empty() stack$pop() [1] "abc" stack$pop() stack$pop() stack$pop()
212Stack
13r
ieqo5
qsort [] = [] qsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y <- xs, y >= x]
230Sorting algorithms/Quicksort
8haskell
9dkmo
def insertionSort = { list -> def size = list.size() (1..<size).each { i -> def value = list[i] def j = i - 1 for (; j >= 0 && list[j] > value; j--) { print "."; list[j+1] = list[j] } print "."; list[j+1] = value } list }
229Sorting algorithms/Insertion sort
7groovy
j2o7o
import Data.List (insert) insertionSort :: Ord a => [a] -> [a] insertionSort = foldr insert []
229Sorting algorithms/Insertion sort
8haskell
tsgf7
public static void heapSort(int[] a){ int count = a.length;
231Sorting algorithms/Heapsort
9java
z04tq
function heapSort(arr) { heapify(arr) end = arr.length - 1 while (end > 0) { [arr[end], arr[0]] = [arr[0], arr[end]] end-- siftDown(arr, 0, end) } } function heapify(arr) { start = Math.floor(arr.length/2) - 1 while (start >= 0) { siftDown(arr, start, arr.length - 1) start-- } } function siftDown(arr, startPos, endPos) { let rootPos = startPos while (rootPos * 2 + 1 <= endPos) { childPos = rootPos * 2 + 1 if (childPos + 1 <= endPos && arr[childPos] < arr[childPos + 1]) { childPos++ } if (arr[rootPos] < arr[childPos]) { [arr[rootPos], arr[childPos]] = [arr[childPos], arr[rootPos]] rootPos = childPos } else { return } } } test('rosettacode', () => { arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8,] heapSort(arr) expect(arr).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) })
231Sorting algorithms/Heapsort
10javascript
9dhml
def sequential_sort(array) sorted = [] while array.any? index_of_smallest_element = find_smallest_index(array) sorted << array.delete_at(index_of_smallest_element) end sorted end def find_smallest_index(array) smallest_element = array[0] smallest_index = 0 array.each_with_index do |ele, idx| if ele < smallest_element smallest_element = ele smallest_index = idx end end smallest_index end puts def sequential_sort_with_swapping(array) array.each_with_index do |element, index| smallest_unsorted_element_so_far = element smallest_unsorted_index_so_far = index (index+1...array.length).each do |index_value| if array[index_value] < smallest_unsorted_element_so_far smallest_unsorted_element_so_far = array[index_value] smallest_unsorted_index_so_far = index_value end end array[index], array[smallest_unsorted_index_so_far] = array[smallest_unsorted_index_so_far], array[index] end array end puts
226Sorting algorithms/Selection sort
14ruby
mn1yj
null
231Sorting algorithms/Heapsort
11kotlin
ielo4
fn selection_sort(array: &mut [i32]) { let mut min; for i in 0..array.len() { min = i; for j in (i+1)..array.len() { if array[j] < array[min] { min = j; } } let tmp = array[i]; array[i] = array[min]; array[min] = tmp; } } fn main() { let mut array = [ 9, 4, 8, 3, -5, 2, 1, 6 ]; println!("The initial array is {:?}", array); selection_sort(&mut array); println!(" The sorted array is {:?}", array); }
226Sorting algorithms/Selection sort
15rust
9damm
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} var s = make([]int, len(a)/2+1)
232Sorting algorithms/Merge sort
0go
iecog
def swap(a: Array[Int], i1: Int, i2: Int) = { val tmp = a(i1); a(i1) = a(i2); a(i2) = tmp } def selectionSort(a: Array[Int]) = for (i <- 0 until a.size - 1) swap(a, i, (i + 1 until a.size).foldLeft(i)((currMin, index) => if (a(index) < a(currMin)) index else currMin))
226Sorting algorithms/Selection sort
16scala
2zxlb
def merge = { List left, List right -> List mergeList = [] while (left && right) { print "." mergeList << ((left[-1] > right[-1]) ? left.pop(): right.pop()) } mergeList = mergeList.reverse() mergeList = left + right + mergeList } def mergeSort; mergeSort = { List list -> def n = list.size() if (n < 2) return list def middle = n.intdiv(2) def left = [] + list[0..<middle] def right = [] + list[middle..<n] left = mergeSort(left) right = mergeSort(right) if (left[-1] <= right[0]) return left + right merge(left, right) }
232Sorting algorithms/Merge sort
7groovy
qk3xp
public static <E extends Comparable<? super E>> List<E> quickSort(List<E> arr) { if (arr.isEmpty()) return arr; else { E pivot = arr.get(0); List<E> less = new LinkedList<E>(); List<E> pivotList = new LinkedList<E>(); List<E> more = new LinkedList<E>();
230Sorting algorithms/Quicksort
9java
ts4f9
merge [] ys = ys merge xs [] = xs merge xs@(x:xt) ys@(y:yt) | x <= y = x: merge xt ys | otherwise = y: merge xs yt split (x:y:zs) = let (xs,ys) = split zs in (x:xs,y:ys) split [x] = ([x],[]) split [] = ([],[]) mergeSort [] = [] mergeSort [x] = [x] mergeSort xs = let (as,bs) = split xs in merge (mergeSort as) (mergeSort bs)
232Sorting algorithms/Merge sort
8haskell
v3p2k
stack = [] stack.push(value) value = stack.pop stack.empty?
212Stack
14ruby
38nz7
function sort(array, less) { function swap(i, j) { var t = array[i]; array[i] = array[j]; array[j] = t; } function quicksort(left, right) { if (left < right) { var pivot = array[left + Math.floor((right - left) / 2)], left_new = left, right_new = right; do { while (less(array[left_new], pivot)) { left_new += 1; } while (less(pivot, array[right_new])) { right_new -= 1; } if (left_new <= right_new) { swap(left_new, right_new); left_new += 1; right_new -= 1; } } while (left_new <= right_new); quicksort(left, right_new); quicksort(left_new, right); } } quicksort(0, array.length - 1); return array; }
230Sorting algorithms/Quicksort
10javascript
mnhyv
public static void insertSort(int[] A){ for(int i = 1; i < A.length; i++){ int value = A[i]; int j = i - 1; while(j >= 0 && A[j] > value){ A[j + 1] = A[j]; j = j - 1; } A[j + 1] = value; } }
229Sorting algorithms/Insertion sort
9java
81l06
func selectionSort(inout arr:[Int]) { var min:Int for n in 0..<arr.count { min = n for x in n+1..<arr.count { if (arr[x] < arr[min]) { min = x } } if min!= n { let temp = arr[min] arr[min] = arr[n] arr[n] = temp } } }
226Sorting algorithms/Selection sort
17swift
yip6e
function insertionSort (a) { for (var i = 0; i < a.length; i++) { var k = a[i]; for (var j = i; j > 0 && k < a[j - 1]; j--) a[j] = a[j - 1]; a[j] = k; } return a; } var a = [4, 65, 2, -31, 0, 99, 83, 782, 1]; insertionSort(a); document.write(a.join(" "));
229Sorting algorithms/Insertion sort
10javascript
fq4dg
fn main() { let mut stack = Vec::new(); stack.push("Element1"); stack.push("Element2"); stack.push("Element3"); assert_eq!(Some(&"Element3"), stack.last()); assert_eq!(Some("Element3"), stack.pop()); assert_eq!(Some("Element2"), stack.pop()); assert_eq!(Some("Element1"), stack.pop()); assert_eq!(None, stack.pop()); }
212Stack
15rust
6od3l
class Stack[T] { private var items = List[T]() def isEmpty = items.isEmpty def peek = items match { case List() => error("Stack empty") case head :: rest => head } def pop = items match { case List() => error("Stack empty") case head :: rest => items = rest; head } def push(value: T) = items = value +: items }
212Stack
16scala
9dzm5
fun insertionSort(array: IntArray) { for (index in 1 until array.size) { val value = array[index] var subIndex = index - 1 while (subIndex >= 0 && array[subIndex] > value) { array[subIndex + 1] = array[subIndex] subIndex-- } array[subIndex + 1] = value } } fun main(args: Array<String>) { val numbers = intArrayOf(5, 2, 3, 17, 12, 1, 8, 3, 4, 9, 7) fun printArray(message: String, array: IntArray) = with(array) { print("$message [") forEachIndexed { index, number -> print(if (index == lastIndex) number else "$number, ") } println("]") } printArray("Unsorted:", numbers) insertionSort(numbers) printArray("Sorted:", numbers) }
229Sorting algorithms/Insertion sort
11kotlin
wj6ek
import java.util.List; import java.util.ArrayList; import java.util.Iterator; public class Merge{ public static <E extends Comparable<? super E>> List<E> mergeSort(List<E> m){ if(m.size() <= 1) return m; int middle = m.size() / 2; List<E> left = m.subList(0, middle); List<E> right = m.subList(middle, m.size()); right = mergeSort(right); left = mergeSort(left); List<E> result = merge(left, right); return result; } public static <E extends Comparable<? super E>> List<E> merge(List<E> left, List<E> right){ List<E> result = new ArrayList<E>(); Iterator<E> it1 = left.iterator(); Iterator<E> it2 = right.iterator(); E x = it1.next(); E y = it2.next(); while (true){
232Sorting algorithms/Merge sort
9java
yir6g
function merge(left, right, arr) { var a = 0; while (left.length && right.length) { arr[a++] = (right[0] < left[0]) ? right.shift() : left.shift(); } while (left.length) { arr[a++] = left.shift(); } while (right.length) { arr[a++] = right.shift(); } } function mergeSort(arr) { var len = arr.length; if (len === 1) { return; } var mid = Math.floor(len / 2), left = arr.slice(0, mid), right = arr.slice(mid); mergeSort(left); mergeSort(right); merge(left, right, arr); } var arr = [1, 5, 2, 7, 3, 9, 4, 6, 8]; mergeSort(arr);
232Sorting algorithms/Merge sort
10javascript
2zblr
fun <E : Comparable<E>> List<E>.qsort(): List<E> = if (size < 2) this else filter { it < first() }.qsort() + filter { it == first() } + filter { it > first() }.qsort()
230Sorting algorithms/Quicksort
11kotlin
oal8z
my @a = (4, 65, 2, -31, 0, 99, 2, 83, 782, 1); print "@a\n"; heap_sort(\@a); print "@a\n"; sub heap_sort { my ($a) = @_; my $n = @$a; for (my $i = ($n - 2) / 2; $i >= 0; $i--) { down_heap($a, $n, $i); } for (my $i = 0; $i < $n; $i++) { my $t = $a->[$n - $i - 1]; $a->[$n - $i - 1] = $a->[0]; $a->[0] = $t; down_heap($a, $n - $i - 1, 0); } } sub down_heap { my ($a, $n, $i) = @_; while (1) { my $j = max($a, $n, $i, 2 * $i + 1, 2 * $i + 2); last if $j == $i; my $t = $a->[$i]; $a->[$i] = $a->[$j]; $a->[$j] = $t; $i = $j; } } sub max { my ($a, $n, $i, $j, $k) = @_; my $m = $i; $m = $j if $j < $n && $a->[$j] > $a->[$m]; $m = $k if $k < $n && $a->[$k] > $a->[$m]; return $m; }
231Sorting algorithms/Heapsort
2perl
rcqgd
do local function lower_bound(container, container_begin, container_end, value, comparator) local count = container_end - container_begin + 1 while count > 0 do local half = bit.rshift(count, 1)
229Sorting algorithms/Insertion sort
1lua
xhywz
fun mergeSort(list: List<Int>): List<Int> { if (list.size <= 1) { return list } val left = mutableListOf<Int>() val right = mutableListOf<Int>() val middle = list.size / 2 list.forEachIndexed { index, number -> if (index < middle) { left.add(number) } else { right.add(number) } } fun merge(left: List<Int>, right: List<Int>): List<Int> = mutableListOf<Int>().apply { var indexLeft = 0 var indexRight = 0 while (indexLeft < left.size && indexRight < right.size) { if (left[indexLeft] <= right[indexRight]) { add(left[indexLeft]) indexLeft++ } else { add(right[indexRight]) indexRight++ } } while (indexLeft < left.size) { add(left[indexLeft]) indexLeft++ } while (indexRight < right.size) { add(right[indexRight]) indexRight++ } } return merge(mergeSort(left), mergeSort(right)) } fun main(args: Array<String>) { val numbers = listOf(5, 2, 3, 17, 12, 1, 8, 3, 4, 9, 7) println("Unsorted: $numbers") println("Sorted: ${mergeSort(numbers)}") }
232Sorting algorithms/Merge sort
11kotlin
fqvdo
table.sort(tableName)
230Sorting algorithms/Quicksort
1lua
ie2ot
struct Stack<T> { var items = [T]() var empty:Bool { return items.count == 0 } func peek() -> T { return items[items.count - 1] } mutating func pop() -> T { return items.removeLast() } mutating func push(obj:T) { items.append(obj) } } var stack = Stack<Int>() stack.push(1) stack.push(2) println(stack.pop()) println(stack.peek()) stack.pop() println(stack.empty)
212Stack
17swift
z0itu
local function merge(left_container, left_container_begin, left_container_end, right_container, right_container_begin, right_container_end, result_container, result_container_begin, comparator) while left_container_begin <= left_container_end do if right_container_begin > right_container_end then for i = left_container_begin, left_container_end do result_container[result_container_begin] = left_container[i] result_container_begin = result_container_begin + 1 end return end if comparator(right_container[right_container_begin], left_container[left_container_begin]) then result_container[result_container_begin] = right_container[right_container_begin] right_container_begin = right_container_begin + 1 else result_container[result_container_begin] = left_container[left_container_begin] left_container_begin = left_container_begin + 1 end result_container_begin = result_container_begin + 1 end for i = right_container_begin, right_container_end do result_container[result_container_begin] = right_container[i] result_container_begin = result_container_begin + 1 end end local function mergesort_impl(container, container_begin, container_end, comparator) local range_length = (container_end - container_begin) + 1 if range_length < 2 then return end local copy = {} local copy_len = 0 for it = container_begin, container_end do copy_len = copy_len + 1 copy[copy_len] = container[it] end local middle = bit.rshift(range_length, 1)
232Sorting algorithms/Merge sort
1lua
tsufn
def heapsort(lst): ''' Heapsort. Note: this function sorts in-place (it mutates the list). ''' for start in range((len(lst)-2)/2, -1, -1): siftdown(lst, start, len(lst)-1) for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] siftdown(lst, 0, end - 1) return lst def siftdown(lst, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] root = child else: break
231Sorting algorithms/Heapsort
3python
7lsrm
class Array def heapsort self.dup.heapsort! end def heapsort! ((length - 2) / 2).downto(0) {|start| siftdown(start, length - 1)} (length - 1).downto(1) do |end_| self[end_], self[0] = self[0], self[end_] siftdown(0, end_ - 1) end self end def siftdown(start, end_) root = start loop do child = root * 2 + 1 break if child > end_ if child + 1 <= end_ and self[child] < self[child + 1] child += 1 end if self[root] < self[child] self[root], self[child] = self[child], self[root] root = child else break end end end end
231Sorting algorithms/Heapsort
14ruby
hv8jx
fn main() { let mut v = [4, 6, 8, 1, 0, 3, 2, 2, 9, 5]; heap_sort(&mut v, |x, y| x < y); println!("{:?}", v); } fn heap_sort<T, F>(array: &mut [T], order: F) where F: Fn(&T, &T) -> bool, { let len = array.len();
231Sorting algorithms/Heapsort
15rust
kuoh5
def heapSort[T](a: Array[T])(implicit ord: Ordering[T]) { import scala.annotation.tailrec
231Sorting algorithms/Heapsort
16scala
1gdpf
func heapsort<T:Comparable>(inout list:[T]) { var count = list.count func shiftDown(inout list:[T], start:Int, end:Int) { var root = start while root * 2 + 1 <= end { var child = root * 2 + 1 var swap = root if list[swap] < list[child] { swap = child } if child + 1 <= end && list[swap] < list[child + 1] { swap = child + 1 } if swap == root { return } else { (list[root], list[swap]) = (list[swap], list[root]) root = swap } } } func heapify(inout list:[T], count:Int) { var start = (count - 2) / 2 while start >= 0 { shiftDown(&list, start, count - 1) start-- } } heapify(&list, count) var end = count - 1 while end > 0 { (list[end], list[0]) = (list[0], list[end]) end-- shiftDown(&list, 0, end) } }
231Sorting algorithms/Heapsort
17swift
j2074
sub insertion_sort { my (@list) = @_; foreach my $i (1 .. $ my $j = $i; my $k = $list[$i]; while ( $j > 0 && $k < $list[$j - 1]) { $list[$j] = $list[$j - 1]; $j--; } $list[$j] = $k; } return @list; } my @a = insertion_sort(4, 65, 2, -31, 0, 99, 83, 782, 1); print "@a\n";
229Sorting algorithms/Insertion sort
2perl
lt1c5
function insertionSort(&$arr){ for($i=0;$i<count($arr);$i++){ $val = $arr[$i]; $j = $i-1; while($j>=0 && $arr[$j] > $val){ $arr[$j+1] = $arr[$j]; $j--; } $arr[$j+1] = $val; } } $arr = array(4,2,1,6,9,3,8,7); insertionSort($arr); echo implode(',',$arr);
229Sorting algorithms/Insertion sort
12php
qkmx3
sub merge_sort { my @x = @_; return @x if @x < 2; my $m = int @x / 2; my @a = merge_sort(@x[0 .. $m - 1]); my @b = merge_sort(@x[$m .. $ for (@x) { $_ = !@a ? shift @b : !@b ? shift @a : $a[0] <= $b[0] ? shift @a : shift @b; } @x; } my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1); @a = merge_sort @a; print "@a\n";
232Sorting algorithms/Merge sort
2perl
hv0jl
function mergesort($arr){ if(count($arr) == 1 ) return $arr; $mid = count($arr) / 2; $left = array_slice($arr, 0, $mid); $right = array_slice($arr, $mid); $left = mergesort($left); $right = mergesort($right); return merge($left, $right); } function merge($left, $right){ $res = array(); while (count($left) > 0 && count($right) > 0){ if($left[0] > $right[0]){ $res[] = $right[0]; $right = array_slice($right , 1); }else{ $res[] = $left[0]; $left = array_slice($left, 1); } } while (count($left) > 0){ $res[] = $left[0]; $left = array_slice($left, 1); } while (count($right) > 0){ $res[] = $right[0]; $right = array_slice($right, 1); } return $res; } $arr = array( 1, 5, 2, 7, 3, 9, 4, 6, 8); $arr = mergesort($arr); echo implode(',',$arr);
232Sorting algorithms/Merge sort
12php
z05t1
def insertion_sort(L): for i in xrange(1, len(L)): j = i-1 key = L[i] while j >= 0 and L[j] > key: L[j+1] = L[j] j -= 1 L[j+1] = key
229Sorting algorithms/Insertion sort
3python
2zalz
from heapq import merge def merge_sort(m): if len(m) <= 1: return m middle = len(m) left = m[:middle] right = m[middle:] left = merge_sort(left) right = merge_sort(right) return list(merge(left, right))
232Sorting algorithms/Merge sort
3python
ku8hf
void swap(char* p1, char* p2, size_t size) { for (; size-- > 0; ++p1, ++p2) { char tmp = *p1; *p1 = *p2; *p2 = tmp; } } void cocktail_shaker_sort(void* base, size_t count, size_t size, int (*cmp)(const void*, const void*)) { char* begin = base; char* end = base + size * count; if (end == begin) return; for (end -= size; begin < end; ) { char* new_begin = end; char* new_end = begin; for (char* p = begin; p < end; p += size) { char* q = p + size; if (cmp(p, q) > 0) { swap(p, q, size); new_end = p; } } end = new_end; for (char* p = end; p > begin; p -= size) { char* q = p - size; if (cmp(q, p) > 0) { swap(p, q, size); new_begin = p; } } begin = new_begin; } } int string_compare(const void* p1, const void* p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } void print(const char** a, size_t len) { for (size_t i = 0; i < len; ++i) printf(, a[i]); printf(); } int main() { const char* a[] = { , , , , , , , }; const size_t len = sizeof(a)/sizeof(a[0]); printf(); print(a, len); cocktail_shaker_sort(a, len, sizeof(char*), string_compare); printf(); print(a, len); return 0; }
233Sorting algorithms/Cocktail sort with shifting bounds
5c
2zklo
insertionsort <- function(x) { for(i in 2:(length(x))) { value <- x[i] j <- i - 1 while(j >= 1 && x[j] > value) { x[j+1] <- x[j] j <- j-1 } x[j+1] <- value } x } insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1))
229Sorting algorithms/Insertion sort
13r
mnky4
sub quick_sort { return @_ if @_ < 2; my $p = splice @_, int rand @_, 1; quick_sort(grep $_ < $p, @_), $p, quick_sort(grep $_ >= $p, @_); } my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1); @a = quick_sort @a; print "@a\n";
230Sorting algorithms/Quicksort
2perl
g9q4e
mergesort <- function(m) { merge_ <- function(left, right) { result <- c() while(length(left) > 0 && length(right) > 0) { if(left[1] <= right[1]) { result <- c(result, left[1]) left <- left[-1] } else { result <- c(result, right[1]) right <- right[-1] } } if(length(left) > 0) result <- c(result, left) if(length(right) > 0) result <- c(result, right) result } len <- length(m) if(len <= 1) m else { middle <- length(m) / 2 left <- m[1:floor(middle)] right <- m[floor(middle+1):len] left <- mergesort(left) right <- mergesort(right) if(left[length(left)] <= right[1]) { c(left, right) } else { merge_(left, right) } } } mergesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1))
232Sorting algorithms/Merge sort
13r
rcxgj
function quicksort($arr){ $lte = $gt = array(); if(count($arr) < 2){ return $arr; } $pivot_key = key($arr); $pivot = array_shift($arr); foreach($arr as $val){ if($val <= $pivot){ $lte[] = $val; } else { $gt[] = $val; } } return array_merge(quicksort($lte),array($pivot_key=>$pivot),quicksort($gt)); } $arr = array(1, 3, 5, 7, 9, 8, 6, 4, 2); $arr = quicksort($arr); echo implode(',',$arr);
230Sorting algorithms/Quicksort
12php
nwvig
package main import ( "fmt" "math/rand" "time" )
233Sorting algorithms/Cocktail sort with shifting bounds
0go
qkzxz
class CocktailSort { static void main(String[] args) { Integer[] array = [ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 ] println("before: " + Arrays.toString(array)) cocktailSort(array) println("after: " + Arrays.toString(array)) }
233Sorting algorithms/Cocktail sort with shifting bounds
7groovy
1gip6
import java.util.*; public class CocktailSort { public static void main(String[] args) { Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 }; System.out.println("before: " + Arrays.toString(array)); cocktailSort(array); System.out.println("after: " + Arrays.toString(array)); }
233Sorting algorithms/Cocktail sort with shifting bounds
9java
fq2dv
fun <T> swap(array: Array<T>, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } fun <T> cocktailSort(array: Array<T>) where T : Comparable<T> { var begin = 0 var end = array.size if (end == 0) { return } --end while (begin < end) { var newBegin = end var newEnd = begin for (i in begin until end) { val c1 = array[i] val c2 = array[i + 1] if (c1 > c2) { swap(array, i, i + 1) newEnd = i } } end = newEnd for (i in end downTo begin + 1) { val c1 = array[i - 1] val c2 = array[i] if (c1 > c2) { swap(array, i, i - 1) newBegin = i } } begin = newBegin } } fun main() { val array: Array<Int> = intArrayOf(5, 1, -6, 12, 3, 13, 2, 4, 0, 15).toList().toTypedArray() println("before: ${array.contentToString()}") cocktailSort(array) println("after: ${array.contentToString()}") }
233Sorting algorithms/Cocktail sort with shifting bounds
11kotlin
81y0q
def merge_sort(m) return m if m.length <= 1 middle = m.length / 2 left = merge_sort(m[0...middle]) right = merge_sort(m[middle..-1]) merge(left, right) end def merge(left, right) result = [] until left.empty? || right.empty? result << (left.first<=right.first? left.shift: right.shift) end result + left + right end ary = [7,6,5,9,8,4,3,1,2,0] p merge_sort(ary)
232Sorting algorithms/Merge sort
14ruby
p4ibh
class Array def insertionsort! 1.upto(length - 1) do |i| value = self[i] j = i - 1 while j >= 0 and self[j] > value self[j+1] = self[j] j -= 1 end self[j+1] = value end self end end ary = [7,6,5,9,8,4,3,1,2,0] p ary.insertionsort!
229Sorting algorithms/Insertion sort
14ruby
u6wvz
fn merge<T: Copy + PartialOrd>(x1: &[T], x2: &[T], y: &mut [T]) { assert_eq!(x1.len() + x2.len(), y.len()); let mut i = 0; let mut j = 0; let mut k = 0; while i < x1.len() && j < x2.len() { if x1[i] < x2[j] { y[k] = x1[i]; k += 1; i += 1; } else { y[k] = x2[j]; k += 1; j += 1; } } if i < x1.len() { y[k..].copy_from_slice(&x1[i..]); } if j < x2.len() { y[k..].copy_from_slice(&x2[j..]); } }
232Sorting algorithms/Merge sort
15rust
1gnpu
use strict; use warnings; use feature 'say'; sub cocktail_sort { my @a = @_; my ($min, $max) = (0, $ while (1) { my $swapped_forward = 0; for my $i ($min .. $max) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1 } } last if not $swapped_forward; $max -= 1; my $swapped_backward = 0; for my $i (reverse $min .. $max) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_backward = 1; } } last if not $swapped_backward; $min += 1; } @a } say join ' ', cocktail_sort( <t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g> );
233Sorting algorithms/Cocktail sort with shifting bounds
2perl
4ma5d
import scala.language.implicitConversions object MergeSort extends App { def mergeSort(input: List[Int]): List[Int] = { def merge(left: List[Int], right: List[Int]): LazyList[Int] = (left, right) match { case (x :: xs, y :: ys) if x <= y => x #:: merge(xs, right) case (x :: xs, y :: ys) => y #:: merge(left, ys) case _ => if (left.isEmpty) right.to(LazyList) else left.to(LazyList) } def sort(input: List[Int], length: Int): List[Int] = input match { case Nil | List(_) => input case _ => val middle = length / 2 val (left, right) = input splitAt middle merge(sort(left, middle), sort(right, middle + length % 2)).toList } sort(input, input.length) } }
232Sorting algorithms/Merge sort
16scala
wjtes
fn insertion_sort<T: std::cmp::Ord>(arr: &mut [T]) { for i in 1..arr.len() { let mut j = i; while j > 0 && arr[j] < arr[j-1] { arr.swap(j, j-1); j = j-1; } } }
229Sorting algorithms/Insertion sort
15rust
5yxuq
def quickSort(arr): less = [] pivotList = [] more = [] if len(arr) <= 1: return arr else: pivot = arr[0] for i in arr: if i < pivot: less.append(i) elif i > pivot: more.append(i) else: pivotList.append(i) less = quickSort(less) more = quickSort(more) return less + pivotList + more a = [4, 65, 2, -31, 0, 99, 83, 782, 1] a = quickSort(a)
230Sorting algorithms/Quicksort
3python
rcsgq
def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1 while beginIdx <= endIdx: newBeginIdx = endIdx newEndIdx = beginIdx for ii in range(beginIdx,endIdx): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newEndIdx = ii endIdx = newEndIdx for ii in range(endIdx,beginIdx-1,-1): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newBeginIdx = ii beginIdx = newBeginIdx + 1 test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] cocktailshiftingbounds(test1) print(test1) test2=list('big fjords vex quick waltz nymph') cocktailshiftingbounds(test2) print(''.join(test2))
233Sorting algorithms/Cocktail sort with shifting bounds
3python
g9e4h
def insertSort[X](list: List[X])(implicit ord: Ordering[X]) = { def insert(list: List[X], value: X) = list.span(x => ord.lt(x, value)) match { case (lower, upper) => lower ::: value :: upper } list.foldLeft(List.empty[X])(insert) }
229Sorting algorithms/Insertion sort
16scala
rc0gn
qsort <- function(v) { if ( length(v) > 1 ) { pivot <- (min(v) + max(v))/2.0 c(qsort(v[v < pivot]), v[v == pivot], qsort(v[v > pivot])) } else v } N <- 100 vs <- runif(N) system.time(u <- qsort(vs)) print(u)
230Sorting algorithms/Quicksort
13r
u6evx
fn cocktail_shaker_sort<T: PartialOrd>(a: &mut [T]) { let mut begin = 0; let mut end = a.len(); if end == 0 { return; } end -= 1; while begin < end { let mut new_begin = end; let mut new_end = begin; for i in begin..end { if a[i + 1] < a[i] { a.swap(i, i + 1); new_end = i; } } end = new_end; let mut i = end; while i > begin { if a[i] < a[i - 1] { a.swap(i, i - 1); new_begin = i; } i -= 1; } begin = new_begin; } } fn main() { let mut v = vec![5, 1, -6, 12, 3, 13, 2, 4, 0, 15]; println!("before: {:?}", v); cocktail_shaker_sort(&mut v); println!("after: {:?}", v); }
233Sorting algorithms/Cocktail sort with shifting bounds
15rust
j2q72
func cocktailShakerSort<T: Comparable>(_ a: inout [T]) { var begin = 0 var end = a.count if end == 0 { return } end -= 1 while begin < end { var new_begin = end var new_end = begin var i = begin while i < end { if a[i + 1] < a[i] { a.swapAt(i, i + 1) new_end = i } i += 1 } end = new_end i = end while i > begin { if a[i] < a[i - 1] { a.swapAt(i, i - 1) new_begin = i } i -= 1 } begin = new_begin } } var array = [5, 1, -6, 12, 3, 13, 2, 4, 0, 15] print("before: \(array)") cocktailShakerSort(&array) print(" after: \(array)") var array2 = ["one", "two", "three", "four", "five", "six", "seven", "eight"] print("before: \(array2)") cocktailShakerSort(&array2) print(" after: \(array2)")
233Sorting algorithms/Cocktail sort with shifting bounds
17swift
rcwgg
null
232Sorting algorithms/Merge sort
17swift
b5okd
func insertionSort<T:Comparable>(inout list:[T]) { for i in 1..<list.count { var j = i while j > 0 && list[j - 1] > list[j] { swap(&list[j], &list[j - 1]) j-- } } }
229Sorting algorithms/Insertion sort
17swift
v3e2r
class Array def quick_sort return self if length <= 1 pivot = self[0] less, greatereq = self[1..-1].partition { |x| x < pivot } less.quick_sort + [pivot] + greatereq.quick_sort end end
230Sorting algorithms/Quicksort
14ruby
j287x
int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf(, x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); } int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x)); return 0; }
234Sorting Algorithms/Circle Sort
5c
nw9i6
fn main() { println!("Sort numbers in descending order"); let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; println!("Before: {:?}", numbers); quick_sort(&mut numbers, &|x,y| x > y); println!("After: {:?}\n", numbers); println!("Sort strings alphabetically"); let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"]; println!("Before: {:?}", strings); quick_sort(&mut strings, &|x,y| x < y); println!("After: {:?}\n", strings); println!("Sort strings by length"); println!("Before: {:?}", strings); quick_sort(&mut strings, &|x,y| x.len() < y.len()); println!("After: {:?}", strings); } fn quick_sort<T,F>(v: &mut [T], f: &F) where F: Fn(&T,&T) -> bool { let len = v.len(); if len >= 2 { let pivot_index = partition(v, f); quick_sort(&mut v[0..pivot_index], f); quick_sort(&mut v[pivot_index + 1..len], f); } } fn partition<T,F>(v: &mut [T], f: &F) -> usize where F: Fn(&T,&T) -> bool { let len = v.len(); let pivot_index = len / 2; let last_index = len - 1; v.swap(pivot_index, last_index); let mut store_index = 0; for i in 0..last_index { if f(&v[i], &v[last_index]) { v.swap(i, store_index); store_index += 1; } } v.swap(store_index, len - 1); store_index }
230Sorting algorithms/Quicksort
15rust
hvoj2
def sort(xs: List[Int]): List[Int] = xs match { case Nil => Nil case head :: tail => val (less, notLess) = tail.partition(_ < head)
230Sorting algorithms/Quicksort
16scala
p4dbj
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circleSort(a, low, low+mid, swaps) swaps = circleSort(a, low+mid+1, high, swaps) return swaps } func main() { aa := [][]int{ {6, 7, 8, 9, 2, 5, 3, 4, 1}, {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}, } for _, a := range aa { fmt.Printf("Original:%v\n", a) for circleSort(a, 0, len(a)-1, 0) != 0 {
234Sorting Algorithms/Circle Sort
0go
rcegm
import Data.Bool (bool) circleSort :: Ord a => [a] -> [a] circleSort xs = if swapped then circleSort ks else ks where (swapped,ks) = go False xs (False,[]) go d [] sks = sks go d [x] (s,ks) = (s,x:ks) go d xs (s,ks) = let (st,_,ls,rs) = halve d s xs xs in go False ls (go True rs (st,ks)) halve d s (y:ys) (_:_:zs) = swap d y (halve d s ys zs) halve d s ys [] = (s,ys,[],[]) halve d s (y:ys) [_] = (s,ys,[y | e],[y | not e]) where e = y <= head ys swap d x (s,y:ys,ls,rs) | bool (<=) (<) d x y = ( d || s,ys,x:ls,y:rs) | otherwise = (not d || s,ys,y:ls,x:rs)
234Sorting Algorithms/Circle Sort
8haskell
0p3s7
func quicksort<T where T: Comparable>(inout elements: [T], range: Range<Int>) { if (range.endIndex - range.startIndex > 1) { let pivotIndex = partition(&elements, range) quicksort(&elements, range.startIndex ..< pivotIndex) quicksort(&elements, pivotIndex+1 ..< range.endIndex) } } func quicksort<T where T: Comparable>(inout elements: [T]) { quicksort(&elements, indices(elements)) }
230Sorting algorithms/Quicksort
17swift
7l0rq
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toString(arr)); } while (circleSortR(arr, 0, arr.length - 1, 0) != 0); } private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps; int high = hi; int low = lo; int mid = (hi - lo) / 2; while (lo < hi) { if (arr[lo] > arr[hi]) { swap(arr, lo, hi); numSwaps++; } lo++; hi--; } if (lo == hi && arr[lo] > arr[hi + 1]) { swap(arr, lo, hi + 1); numSwaps++; } numSwaps = circleSortR(arr, low, low + mid, numSwaps); numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps); return numSwaps; } private static void swap(int[] arr, int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } }
234Sorting Algorithms/Circle Sort
9java
ari1y
null
234Sorting Algorithms/Circle Sort
11kotlin
hvqj3
null
234Sorting Algorithms/Circle Sort
1lua
kush2
export type Comparator<T> = (o1: T, o2: T) => number; export function quickSort<T>(array: T[], compare: Comparator<T>) { if (array.length <= 1 || array == null) { return; } sort(array, compare, 0, array.length - 1); } function sort<T>( array: T[], compare: Comparator<T>, low: number, high: number) { if (low < high) { const partIndex = partition(array, compare, low, high); sort(array, compare, low, partIndex - 1); sort(array, compare, partIndex + 1, high); } } function partition<T>( array: T[], compare: Comparator<T>, low: number, high: number): number { const pivot: T = array[high]; let i: number = low - 1; for (let j = low; j <= high - 1; j++) { if (compare(array[j], pivot) == -1) { i = i + 1; swap(array, i, j) } } if (compare(array[high], array[i + 1]) == -1) { swap(array, i + 1, high); } return i + 1; } function swap<T>(array: T[], i: number, j: number) { const newJ: T = array[i]; array[i] = array[j]; array[j] = newJ; } export function testQuickSort(): void { function numberComparator(o1: number, o2: number): number { if (o1 < o2) { return -1; } else if (o1 == o2) { return 0; } return 1; } let tests: number[][] = [ [], [1], [2, 1], [-1, 2, -3], [3, 16, 8, -5, 6, 4], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5] ]; for (let testArray of tests) { quickSort(testArray, numberComparator); console.log(testArray); } }
230Sorting algorithms/Quicksort
20typescript
81c0i
sub circlesort { our @x; local *x = shift; my($beg,$end) = @_; my $swaps = 0; if ($beg < $end) { my $lo = $beg; my $hi = $end; while ($lo < $hi) { if ($x[$lo] > $x[$hi]) { @x[$lo,$hi] = @x[$hi,$lo]; ++$swaps; } ++$hi if --$hi == ++$lo } $swaps += circlesort(\@x, $beg, $hi); $swaps += circlesort(\@x, $lo, $end); } $swaps; } my @a = <16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88>; while (circlesort(\@a, 0, $
234Sorting Algorithms/Circle Sort
2perl
z0vtb
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps': ''' >>> L = [3, 2, 8, 28, 2,] >>> circle_sort(L) 3 >>> print(L) [2, 2, 3, 8, 28] >>> L = [3, 2, 8, 28,] >>> circle_sort(L) 1 >>> print(L) [2, 3, 8, 28] ''' n = R-L if n < 2: return 0 swaps = 0 m = n for i in range(m): if A[R-(i+1)] < A[L+i]: (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],) swaps += 1 if (n & 1) and (A[L+m] < A[L+m-1]): (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],) swaps += 1 return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R) def circle_sort(L:list)->'sort A in place, returning the number of swaps': swaps = 0 s = 1 while s: s = circle_sort_backend(L, 0, len(L)) swaps += s return swaps if __name__ == '__main__': from random import shuffle for i in range(309): L = list(range(i)) M = L[:] shuffle(L) N = L[:] circle_sort(L) if L != M: print(len(L)) print(N) print(L)
234Sorting Algorithms/Circle Sort
3python
38uzc
void Combsort11(double a[], int nElements) { int i, j, gap, swapped = 1; double temp; gap = nElements; while (gap > 1 || swapped == 1) { gap = gap * 10 / 13; if (gap == 9 || gap == 10) gap = 11; if (gap < 1) gap = 1; swapped = 0; for (i = 0, j = gap; j < nElements; i++, j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; swapped = 1; } } } }
235Sorting algorithms/Comb sort
5c
j2w70
class Array def circle_sort! while _circle_sort!(0, size-1) > 0 end self end private def _circle_sort!(lo, hi, swaps=0) return swaps if lo == hi low, high = lo, hi mid = (lo + hi) / 2 while lo < hi if self[lo] > self[hi] self[lo], self[hi] = self[hi], self[lo] swaps += 1 end lo += 1 hi -= 1 end if lo == hi && self[lo] > self[hi+1] self[lo], self[hi+1] = self[hi+1], self[lo] swaps += 1 end swaps + _circle_sort!(low, mid) + _circle_sort!(mid+1, high) end end ary = [6, 7, 8, 9, 2, 5, 3, 4, 1] puts puts
234Sorting Algorithms/Circle Sort
14ruby
yi46n
fn _circle_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize { if low == high { return swaps; } let mut lo = low; let mut hi = high; let mid = (hi - lo) / 2; let mut s = swaps; while lo < hi { if a[lo] > a[hi] { a.swap(lo, hi); s += 1; } lo += 1; hi -= 1; } if lo == hi { if a[lo] > a[hi + 1] { a.swap(lo, hi + 1); s += 1; } } s = _circle_sort(a, low, low + mid, s); s = _circle_sort(a, low + mid + 1, high, s); return s; } fn circle_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); loop { if _circle_sort(a, 0, len - 1, 0) == 0 { break; } } } fn main() { let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]; println!("before: {:?}", v); circle_sort(&mut v); println!("after: {:?}", v); }
234Sorting Algorithms/Circle Sort
15rust
mngya
object CircleSort extends App { def sort(arr: Array[Int]): Array[Int] = { def circleSortR(arr: Array[Int], _lo: Int, _hi: Int, _numSwaps: Int): Int = { var lo = _lo var hi = _hi var numSwaps = _numSwaps def swap(arr: Array[Int], idx1: Int, idx2: Int): Unit = { val tmp = arr(idx1) arr(idx1) = arr(idx2) arr(idx2) = tmp } if (lo == hi) return numSwaps val (high, low) = (hi, lo) val mid = (hi - lo) / 2 while ( lo < hi) { if (arr(lo) > arr(hi)) { swap(arr, lo, hi) numSwaps += 1 } lo += 1 hi -= 1 } if (lo == hi && arr(lo) > arr(hi + 1)) { swap(arr, lo, hi + 1) numSwaps += 1 } circleSortR(arr, low + mid + 1, high, circleSortR(arr, low, low + mid, numSwaps)) } while (circleSortR(arr, 0, arr.length - 1, 0) != 0)() arr } println(sort(Array[Int](2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1)).mkString(", ")) }
234Sorting Algorithms/Circle Sort
16scala
ltjcq
func circleSort<T: Comparable>(_ array: inout [T]) { func circSort(low: Int, high: Int, swaps: Int) -> Int { if low == high { return swaps } var lo = low var hi = high let mid = (hi - lo) / 2 var s = swaps while lo < hi { if array[lo] > array[hi] { array.swapAt(lo, hi) s += 1 } lo += 1 hi -= 1 } if lo == hi { if array[lo] > array[hi + 1] { array.swapAt(lo, hi + 1) s += 1 } } s = circSort(low: low, high: low + mid, swaps: s) s = circSort(low: low + mid + 1, high: high, swaps: s) return s } while circSort(low: 0, high: array.count - 1, swaps: 0)!= 0 {} } var array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6] print("before: \(array)") circleSort(&array) print(" after: \(array)") var array2 = ["one", "two", "three", "four", "five", "six", "seven", "eight"] print("before: \(array2)") circleSort(&array2) print(" after: \(array2)")
234Sorting Algorithms/Circle Sort
17swift
6o53j
bool is_sorted(int *a, int n) { while ( --n >= 1 ) { if ( a[n] < a[n-1] ) return false; } return true; } void shuffle(int *a, int n) { int i, t, r; for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } } void bogosort(int *a, int n) { while ( !is_sorted(a, n) ) shuffle(a, n); } int main() { int numbers[] = { 1, 10, 9, 7, 3, 0 }; int i; bogosort(numbers, 6); for (i=0; i < 6; i++) printf(, numbers[i]); printf(); }
236Sorting algorithms/Bogosort
5c
ar811
(defn in-order? [order xs] (or (empty? xs) (apply order xs))) (defn bogosort [order xs] (if (in-order? order xs) xs (recur order (shuffle xs)))) (println (bogosort < [7 5 12 1 4 2 23 18]))
236Sorting algorithms/Bogosort
6clojure
sbfqr
void counting_sort_mm(int *array, int n, int min, int max) { int i, j, z; int range = max - min + 1; int *count = malloc(range * sizeof(*array)); for(i = 0; i < range; i++) count[i] = 0; for(i = 0; i < n; i++) count[ array[i] - min ]++; for(i = min, z = 0; i <= max; i++) { for(j = 0; j < count[i - min]; j++) { array[z++] = i; } } free(count); } void min_max(int *array, int n, int *min, int *max) { int i; *min = *max = array[0]; for(i=1; i < n; i++) { if ( array[i] < *min ) { *min = array[i]; } else if ( array[i] > *max ) { *max = array[i]; } } }
237Sorting algorithms/Counting sort
5c
ie3o2
package main import "fmt" func main() { a := []int{170, 45, 75, -90, -802, 24, 2, 66} fmt.Println("before:", a) combSort(a) fmt.Println("after: ", a) } func combSort(a []int) { if len(a) < 2 { return } for gap := len(a); ; { if gap > 1 { gap = gap * 4 / 5 } swapped := false for i := 0; ; { if a[i] > a[i+gap] { a[i], a[i+gap] = a[i+gap], a[i] swapped = true } i++ if i+gap >= len(a) { break } } if gap == 1 && !swapped { break } } }
235Sorting algorithms/Comb sort
0go
fqcd0
def makeSwap = { a, i, j -> print "."; a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j] } def checkSwap = { a, i, j -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } } def combSort = { input -> def swap = checkSwap.curry(input) def size = input.size() def gap = size def swapped = true while (gap != 1 || swapped) { gap = (gap / 1.247330950103979) as int gap = (gap < 1) ? 1: gap swapped = (0..<(size-gap)).any { swap(it, it + gap) } } input }
235Sorting algorithms/Comb sort
7groovy
8130b
import Data.List import Control.Arrow import Control.Monad flgInsert x xs = ((x:xs==) &&& id)$ insert x xs gapSwapping k = (and *** concat. transpose). unzip . map (foldr (\x (b,xs) -> first (b &&)$ flgInsert x xs) (True,[])) . transpose. takeWhile (not.null). unfoldr (Just. splitAt k) combSort xs = (snd. fst) $ until (\((b,_),g)-> b && g==1) (\((_,xs),g) ->(gapSwapping g xs, fg g)) ((False,xs), fg $ length xs) where fg = max 1. truncate. (/1.25). fromIntegral
235Sorting algorithms/Comb sort
8haskell
4mp5s
void gnome_sort(int *a, int n) { int i=1, j=2, t; while(i < n) { if (a[i - 1] > a[i]) { swap(i - 1, i); if (--i) continue; } i = j++; } }
238Sorting algorithms/Gnome sort
5c
v3r2o
(defn gnomesort ([c] (gnomesort c <)) ([c pred] (loop [x [] [y1 & ys:as y] (seq c)] (cond (empty? y) x (empty? x) (recur (list y1) ys) true (let [zx (last x)] (if (pred y1 zx) (recur (butlast x) (concat (list y1 zx) ys)) (recur (concat x (list y1)) ys))))))) (println (gnomesort [3 1 4 1 5 9 2 6 5]))
238Sorting algorithms/Gnome sort
6clojure
rcbg2
public static <E extends Comparable<? super E>> void sort(E[] input) { int gap = input.length; boolean swapped = true; while (gap > 1 || swapped) { if (gap > 1) { gap = (int) (gap / 1.3); } swapped = false; for (int i = 0; i + gap < input.length; i++) { if (input[i].compareTo(input[i + gap]) > 0) { E t = input[i]; input[i] = input[i + gap]; input[i + gap] = t; swapped = true; } } } }
235Sorting algorithms/Comb sort
9java
cfr9h
void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) BEAD(i, j) = 1; for (j = 0; j < max; j++) { for (sum = i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } for (i = len - sum; i < len; i++) BEAD(i, j) = 1; } for (i = 0; i < len; i++) { for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; } free(beads); } int main() { int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(x)/sizeof(x[0]); bead_sort(x, len); for (i = 0; i < len; i++) printf(, x[i]); return 0; }
239Sorting algorithms/Bead sort
5c
9dvm1
null
235Sorting algorithms/Comb sort
10javascript
5ybur
package main import ( "fmt" "math/rand" "sort" "time" ) func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} rand.Seed(time.Now().UnixNano()) fmt.Println("unsorted:", list) temp := make([]int, len(list)) copy(temp, list) for !sort.IntsAreSorted(temp) { for i, v := range rand.Perm(len(list)) { temp[i] = list[v] } } fmt.Println("sorted! ", temp) }
236Sorting algorithms/Bogosort
0go
mn5yi
(defn transpose [xs] (loop [ret [], remain xs] (if (empty? remain) ret (recur (conj ret (map first remain)) (filter not-empty (map rest remain)))))) (defn bead-sort [xs] (->> xs (map #(repeat % 1)) transpose transpose (map #(reduce + %)))) (-> [5 2 4 1 3 3 9] bead-sort println)
239Sorting algorithms/Bead sort
6clojure
u6rvi
package main import ( "fmt" "runtime" "strings" ) var a = []int{170, 45, 75, -90, -802, 24, 2, 66} var aMin, aMax = -1000, 1000 func main() { fmt.Println("before:", a) countingSort(a, aMin, aMax) fmt.Println("after: ", a) } func countingSort(a []int, aMin, aMax int) { defer func() { if x := recover(); x != nil {
237Sorting algorithms/Counting sort
0go
g9b4n
def bogosort = { list -> def n = list.size() while (n > 1 && (1..<n).any{ list[it-1] > list[it] }) { print '.'*n Collections.shuffle(list) } list }
236Sorting algorithms/Bogosort
7groovy
tscfh
def countingSort = { array -> def max = array.max() def min = array.min()
237Sorting algorithms/Counting sort
7groovy
2zrlv
null
235Sorting algorithms/Comb sort
11kotlin
38vz5