------------------------------------------------------------
bubble sort
------------------------------------------------------------
# swaps given two references
def swap(&a, &b) do
t = a; a = b; b = t
end
# sorts given array and returns it
def bubbleSort(arr: Array) do
len = arr.length
for i <- ...len
nswap = 0
for j in i+1...len do
if arr[i] < arr[j] then
swap arr[i], arr[j]
nswap += 1
end
end
break if nswap == 0
end
arr
end
tests = [
[6, 10, 8, 3, 5, 7, 4, 2, 12, 1, 11, 9],
[8, 12, 5, 10, 11, 4, 1, 3, 6, 2, 7, 9],
[11, 9, 4, 10, 3, 7, 5, 1, 2, 12, 8, 6],
]
results = []
for test <- tests
result = test.dup
println tests, " => ", bubbleSort(result)
results << result
end
puts 'test failed!' if not (results[0] == results[1] == results[2])