Last active
November 14, 2016 17:05
-
-
Save travisofthenorth/b5d72567bf28af4eaf85 to your computer and use it in GitHub Desktop.
Ruby merge functions
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
module Sort | |
def mergesort!(a) | |
a.replace(mergesort(a)) | |
end | |
def mergesort(a) | |
return a if a.length <= 1 | |
halfway = a.length / 2 | |
left, right = a[0..halfway - 1], a[halfway..a.length] | |
left = mergesort(left) | |
right = mergesort(right) | |
merge(left, right) | |
end | |
def merge(a, b) | |
result = [] | |
until a.empty? && b.empty? | |
if a.any? && (b.empty? || a[0] <= b[0]) | |
result << a.shift | |
else | |
result << b.shift | |
end | |
end | |
result | |
end | |
def quicksort!(a, low, high) | |
return unless low < high | |
p = partition(a, low, high) | |
quicksort!(a, low, p - 1) | |
quicksort!(a, p + 1, high) | |
end | |
def partition(a, low, high) | |
pivot = a[high] | |
i = low | |
(low..high - 1).each do |j| | |
swap(a, i, j) && i += 1 if a[j] < pivot | |
end | |
swap(a, i, high) | |
i | |
end | |
def swap(a, i, j) | |
return if i == j | |
a[i], a[j] = a[j], a[i] | |
end | |
end | |
require 'Benchmark' | |
include Sort | |
array = (1..100000).map { rand(100000) } | |
quicked = array.dup | |
merged = array.dup | |
Benchmark.bm do |x| | |
x.report('quicksort!') { quicksort!(quicked, 0, quicked.length - 1) } | |
x.report('mergesort!') { mergesort!(merged) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment