Cocktail sort
func cocktailsort(a) {
var swapped = false
func cmpsw(i) {
if (a[i] > a[i+1]) {
a[i, i+1] = a[i+1, i]
swapped = true
}
}
var max = a.end
do {
{|i| cmpsw(i) } << ^max
swapped.not! && break
{|i| cmpsw(max-i) } << 1..max
} while (swapped)
return a
}Test:
var numbers = [7,6,5,9,8,4,3,1,2,0]
say cocktailsort(numbers)
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]
say cocktailsort(strs)Output:
Last updated
Was this helpful?