2010-01-24 18:59:29 -05:00
|
|
|
# An in-place selection sort.
|
2010-07-29 00:03:42 -04:00
|
|
|
selection_sort = (list) ->
|
|
|
|
len = list.length
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# For each item in the list.
|
2010-11-21 11:41:24 -05:00
|
|
|
for i in [0...len]
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# Set the minimum to this position.
|
2010-07-29 00:03:42 -04:00
|
|
|
min = i
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# Check the rest of the array to see if anything is smaller.
|
2010-11-21 11:41:24 -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.
|
2010-07-29 00:03:42 -04:00
|
|
|
[list[i], list[min]] = [list[min], list[i]] if i isnt min
|
2010-01-24 18:59:29 -05:00
|
|
|
|
|
|
|
# The list is now sorted.
|
|
|
|
list
|
|
|
|
|
|
|
|
|
|
|
|
# Test the function.
|
2010-10-24 12:48:42 -04:00
|
|
|
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'
|