jashkenas--coffeescript/examples/computer_science/bubble_sort.coffee

11 lines
388 B
CoffeeScript

# A bubble sort implementation, sorting the given array in-place.
bubble_sort = (list) ->
for i from 0 to list.length - 1
for j from 0 to list.length - i - 1
[list[j], list[j+1]] = [list[j+1], list[j]] if list[j] > list[j+1]
list
# Test the function.
console.log bubble_sort([3, 2, 1]).join(' ') is '1 2 3'
console.log bubble_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9'