Showing posts with label sort. Show all posts
Showing posts with label sort. Show all posts

Saturday, June 3, 2017

Merge sort

Contributed by arpruss.
Usage:
 



function _slice(a,start,end=undef) =
    let(end = end==undef ? len(a) : end)
        start>=end ? [] : [for (i=[start:end-1]) a[i]];

function _mergeLists(a,b,merged=[]) =
    len(a)==0 ? concat(merged,b) :
    len(b)==0 ? concat(merged,a) :
    a[0] < b[0] ? _mergeLists(_slice(a,1), b, merged=concat(merged,[a[0]])) : 
        _mergeLists(_slice(b,1), a, merged=concat(merged,[b[0]]));

function mergeSort(a) =
    let(l=len(a))
        l <= 1 ? a :
        let(split=floor(l/2),
            b=_slice(a,0,end=split),
            c=_slice(a,split))
            _mergeLists(mergeSort(b),mergeSort(c));

echo(mergeSort(rands(0,100,1000)));

 

Friday, May 12, 2017

Quick Sort

Basic quick sort.
Recursively sorts a list of elements


function quicksort(list)= 
!(len(list)>0)?[]:
let(
pivot = list[floor(len(list)/2)],
list_lesser =[ for(i=[0:len(list)-1])if( y[i] < pivot )y[i] ],
list_equal  =[ for(i=[0:len(list)-1])if( y[i]== pivot )y[i] ],
list_greater=[ for(i=[0:len(list)-1])if( y[i] > pivot )y[i] ])

concat(
quicksort(list_lesser),
list_equal,
quicksort(list_greater));

Sorts a list of elements by column col.

function quicksort_col(list,col=0)= 
!(len(list)>0)?[]:
let(
pivot = list[floor(len(list)/2)][col],
list_lesser =[ for(i=[0:len(list)-1])if( list[i][col] < pivot )list[i] ],
list_equal  =[ for(i=[0:len(list)-1])if( list[i][col]== pivot )list[i] ],
list_greater=[ for(i=[0:len(list)-1])if( list[i][col] > pivot )list[i] ])

concat(
quicksort_col(list_lesser),
list_equal,
quicksort_col(list_greater));