/examples/computer_science/selection_sort.coffee

http://github.com/jashkenas/coffee-script · CoffeeScript · 23 lines · 9 code · 7 blank · 7 comment · 3 complexity · f5a98daf3558f59db3692b12ca646831 MD5 · raw file

  1. # An in-place selection sort.
  2. selection_sort = (list) ->
  3. len = list.length
  4. # For each item in the list.
  5. for i in [0...len]
  6. # Set the minimum to this position.
  7. min = i
  8. # Check the rest of the array to see if anything is smaller.
  9. min = k for v, k in list[i+1...] when v < list[min]
  10. # Swap if a smaller item has been found.
  11. [list[i], list[min]] = [list[min], list[i]] if i isnt min
  12. # The list is now sorted.
  13. list
  14. # Test the function.
  15. console.log selection_sort([3, 2, 1]).join(' ') is '1 2 3'
  16. console.log selection_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9'