Created
March 31, 2014 13:12
-
-
Save Harryyan/9891971 to your computer and use it in GitHub Desktop.
ruby实现的两种代码量较少的直接插入排序算法,一种是需要另一个数组,一种是不需要额外数组的
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
#This way is the easy way to do insertion sort, but needs create a new array | |
class InsertionSort | |
def sort_out_of_place(to_sort) | |
sorted = [] | |
to_sort.each do |element| | |
for index in 0..(to_sort.length - 1) | |
sorted.insert(index, element) if to_sort[index] > element | |
end | |
end | |
return to_sort | |
end | |
end | |
#this way does not need to create a new array | |
def sort_in_place(to_sort) | |
# index starts at one, we can skip the first element, since we would | |
# otherwise take it and place it in the first position, which it already is | |
for index in 1..(to_sort.length - 1) | |
for inner_index in 0..(index - 1) | |
if to_sort[inner_index] >= to_sort[index] | |
to_sort.insert(inner_index, to_sort[index]) | |
to_sort.delete_at(index + 1) | |
end | |
end | |
end | |
return to_sort | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment