Last active
December 10, 2015 14:18
-
-
Save rsepassi/4446280 to your computer and use it in GitHub Desktop.
Two array sort methods
This file contains hidden or 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
def sort2(list) | |
unsorted, sorted = list.dup, [] | |
sorted[0] = unsorted.pop | |
while unsorted.size > 0 | |
val = unsorted.pop | |
sorted.each_with_index do |s, i| | |
if val <= s | |
sorted.insert(i, val) | |
break | |
elsif i == (sorted.length - 1) | |
sorted << val | |
break | |
end | |
end | |
end | |
sorted | |
end | |
def sort3(list) | |
unsorted, sorted = list.dup, [] | |
while unsorted.size > 0 | |
sorted.unshift(unsorted.pop) | |
0.upto(sorted.length - 2) do |i| | |
sorted[i], sorted[i+1] = sorted[i+1], sorted[i] if sorted[i] > sorted[i+1] | |
end | |
end | |
sorted | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment