Skip to content

Instantly share code, notes, and snippets.

@mmagm
Created May 12, 2012 14:31
Show Gist options
  • Save mmagm/2666821 to your computer and use it in GitHub Desktop.
Save mmagm/2666821 to your computer and use it in GitHub Desktop.
insertion sort
class Array
def insertion_sort_imperative
self.each_index do |j|
v = self[j]
i = j - 1
while (i >= 0) and (self[i] > v) do
self[i], self[i + 1] = self[i + 1], self[i]
i = i - 1
end
self[i + 1] = v
end
return self
end
def insert(val, array)
return [val] if array.empty?
if val > array[0]
return [array[0]] + insert(val, array[1..-1])
else
return [val] + array
end
end
def insertionsort
arr = []
self.each do |v|
arr = insert(v, arr)
end
return arr
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment