PageRenderTime 38ms CodeModel.GetById 29ms app.highlight 5ms RepoModel.GetById 2ms app.codeStats 0ms

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