Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created March 19, 2013 17:43
Show Gist options
  • Select an option

  • Save ackintosh/5198308 to your computer and use it in GitHub Desktop.

Select an option

Save ackintosh/5198308 to your computer and use it in GitHub Desktop.
Insertion sort in Ruby
class Array
def insertion_sort
inject([]) { |mem, var| mem.insert_with_order(var) }
end
def insert_with_order(var)
pos = find_index { |v| var <= v } || length
insert(pos, var)
end
end
ar = [4,2,1,6,7,34,11,9]
p ar.insertion_sort
# [1, 2, 4, 6, 7, 9, 11, 34]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment