Sha256: 9c61050b6e5b052b9b13b7cec82434098b8bb63824486f878afb5636917c2e49

Contents?: true

Size: 586 Bytes

Versions: 7

Compression:

Stored size: 586 Bytes

Contents

# 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: j if list[j] < list[min]) for j in [(i+1)...len]

    # 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.
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')

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
haml-more-0.5.1 vendor/coffee-script/examples/computer_science/selection_sort.coffee
haml-more-0.5.0 vendor/coffee-script/examples/computer_science/selection_sort.coffee
haml-more-0.4.0 vendor/coffee-script/examples/computer_science/selection_sort.coffee
haml-more-0.4.0.d vendor/coffee-script/examples/computer_science/selection_sort.coffee
haml-more-0.4.0.c vendor/coffee-script/examples/computer_science/selection_sort.coffee
haml-more-0.4.0.b vendor/coffee-script/examples/computer_science/selection_sort.coffee
haml-more-0.4.0.a vendor/coffee-script/examples/computer_science/selection_sort.coffee