Skip to content

Instantly share code, notes, and snippets.

@jedschneider
Last active October 16, 2015 04:30
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 jedschneider/82632771a897f32e6e39 to your computer and use it in GitHub Desktop.
Save jedschneider/82632771a897f32e6e39 to your computer and use it in GitHub Desktop.
class InsertionSort
def initialize(list)
@list = list
@sorted = []
end
def sort
insert(@list.shift) while @list.length > 0
@sorted
end
private
def insert(x)
head = @sorted.select{ |i| i <= x }
tail = @sorted.select{ |i| i > x }
@sorted = head + [x] + tail
end
end
# puts InsertionSort.new([]).sort.inspect
# puts InsertionSort.new([4]).sort.inspect
# puts InsertionSort.new([1, 4]).sort.inspect
# puts InsertionSort.new([4, 1]).sort.inspect
# puts InsertionSort.new([4, 1, 3, 5, 6]).sort.inspect
# puts InsertionSort.new([4, 1, 3, 5, 6, 2]).sort.inspect
# puts InsertionSort.new([4, 1, 3, 5, 6, 2, 2]).sort.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment