File: selection_sort.coffee

package info (click to toggle)
coffeescript 1.10.0~dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,292 kB
  • sloc: makefile: 62
file content (23 lines) | stat: -rw-r--r-- 599 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# An in-place selection sort.
selection_sort = (list) ->
  len = list.length

  # For each item in the list.
  for i in [0...len]

    # Set the minimum to this position.
    min = i

    # Check the rest of the array to see if anything is smaller.
    min = k for v, k in list[i+1...] when v < list[min]

    # Swap if a smaller item has been found.
    [list[i], list[min]] = [list[min], list[i]] if i isnt min

  # The list is now sorted.
  list


# Test the function.
console.log selection_sort([3, 2, 1]).join(' ') is '1 2 3'
console.log selection_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9'