#!/usr/bin/ruby

# https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort

func merge(left, right) {
    gather {
        while (!left.is_empty && !right.is_empty) {
            take([right,left][left.first <= right.first].shift)
        }
    } + left + right
}

func mergesort(arr) {
    var len = arr.len
    len < 2 && return arr
    var (left, right) = arr.part(len // 2)
    merge(__FUNC__(left), __FUNC__(right))
}

# Numeric sort
var nums = @(0..7)
mergesort(nums.shuffle) == nums ||
    die "error(123)";

# String sort
var strings = @('a'..'e');
mergesort(strings.shuffle) == strings ||
    die "error(abc)";

# All OK!
say "** Test passed!";
