Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@EvanHahn
Created October 11, 2012 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvanHahn/3869977 to your computer and use it in GitHub Desktop.
Save EvanHahn/3869977 to your computer and use it in GitHub Desktop.
CoffeeScript selection sort with tests
# Destructive selection sort.
# [1, 12, 8, 5].selectionSort()
Array::selectionSort = ->
# Look forward from each element.
for num, i in this
# Find the smallest element in this partition.
smallest = null
smallestIndex
j = i
while j < @length
if (smallest is null) or (this[j] < smallest)
smallest = this[j]
smallestIndex = j
j++
# Swap the smallest index with the "look forward" element.
[this[i], this[smallestIndex]] = [this[smallestIndex], this[i]]
# All done!
return this
########################################################################
# Test setup
assert = console.assert
eq = (a, b) ->
return false if a.length isnt b.length
for num, i in a
return false if num != b[i]
return true
# Tests
assert eq([].selectionSort(), [])
assert eq([0].selectionSort(), [0])
assert eq([1].selectionSort(), [1])
assert eq([1, 2].selectionSort(), [1, 2])
assert eq([2, 1].selectionSort(), [1, 2])
assert eq([1, 2, 3].selectionSort(), [1, 2, 3])
assert eq([2, 1, 3].selectionSort(), [1, 2, 3])
assert eq([3, 1, 2].selectionSort(), [1, 2, 3])
assert eq([3, 2, 1].selectionSort(), [1, 2, 3])
assert eq([0, 2, 3].selectionSort(), [0, 2, 3])
assert eq([2, 0, 3].selectionSort(), [0, 2, 3])
assert eq([3, 0, 2].selectionSort(), [0, 2, 3])
assert eq([3, 2, 0].selectionSort(), [0, 2, 3])
assert eq([4,3,9,25,25,0,-19,55,43].selectionSort(), [-19,0,3,4,9,25,25,43,55])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment