Created
June 29, 2012 08:52
-
-
Save syohex/3016733 to your computer and use it in GitHub Desktop.
merge sort in ruby
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
#!/usr/bin/env ruby | |
# -*- coding:utf-8 -*- | |
def merge_sort(a) | |
if a.length <= 1 | |
a | |
else | |
(b, c) = split(a) | |
merge( merge_sort(b), merge_sort(c)) | |
end | |
end | |
def split (a) | |
if a.length == 1 | |
[a, []] | |
else | |
half_index = a.length / 2; | |
[a[0..(half_index - 1)], a[half_index..-1]] | |
end | |
end | |
def merge (a, b) | |
if a.empty? | |
b | |
elsif b.empty? | |
a | |
else | |
a_first = a[0] | |
b_first = b[0] | |
if a_first <= b_first | |
a.shift | |
[a_first, *( merge(a, b) )] | |
else | |
b.shift | |
[b_first, *( merge(a, b) )] | |
end | |
end | |
end | |
a = [] | |
20.times do |x| | |
a << (rand 100) | |
end | |
puts "before sort :" | |
p a | |
puts "after sort: " | |
p merge_sort( a ) | |
## before sort : | |
## [61, 57, 30, 57, 79, 74, 0, 56, 21, 89, 8, 20, 76, 57, 28, 27, 92, 50, 67, 42] | |
## after sort: | |
## [0, 8, 20, 21, 27, 28, 30, 42, 50, 56, 57, 57, 57, 61, 67, 74, 76, 79, 89, 92] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment