2010-01-24 18:59:29 -05:00
|
|
|
# An in-place selection sort.
|
2010-01-26 10:52:05 -05:00
|
|
|
selection_sort: (list) ->
|
2010-01-24 18:59:29 -05:00
|
|
|
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.
|
2010-02-07 12:52:07 -05:00
|
|
|
(min: j if list[j] < list[min]) for j in [(i+1)...len]
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# 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.
|
2010-01-29 23:30:54 -05:00
|
|
|
puts(selection_sort([3, 2, 1]).join(' ') is '1 2 3')
|
|
|
|
puts(selection_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9')
|