#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Quickselect_algorithm
#

func quickselect(a, k) {
    var pivot = a.pick;
    var left  = a.grep{|i| i < pivot};
    var right = a.grep{|i| i > pivot};
 
    given(var l = left.len) {
        when(k)     { pivot }
        case(k < l) { __FUNC__(left, k) }
        default     { __FUNC__(right, k - l - 1) }
    }
}
 
var v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4];
var arr = v.range.map{|i| quickselect(v, i)};

say arr;
assert_eq(arr, v.sort);
