Created
May 12, 2012 14:31
-
-
Save mmagm/2666821 to your computer and use it in GitHub Desktop.
insertion sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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