Skip to content

Instantly share code, notes, and snippets.

@yaoyunchen
Last active January 6, 2016 01:47
Show Gist options
  • Save yaoyunchen/7ee4955cba6282721729 to your computer and use it in GitHub Desktop.
Save yaoyunchen/7ee4955cba6282721729 to your computer and use it in GitHub Desktop.
def mergesort(arr)
return arr if arr.count <= 1
#Split array in half.
mid = arr[0..(arr.count / 2) - 1]
#Left side of array.
left = arr[0..mid.count - 1]
#Right side of array.
right = arr[mid.count..arr.count - 1]
#Recursive sort on left and right arrays until size of arrays become 1.
sorted_left = mergesort(left)
sorted_right = mergesort(right)
#Merge the sorted array from left and right until there's nothing left to merge.
sorted_arr = []
until sorted_left.empty? || sorted_right.empty?
if sorted_left.first <= sorted_right.first
#Removes first entry in left array and returns the value.
sorted_arr << sorted_left.shift
else
#Removes first entry in right array and returns the value.
sorted_arr << sorted_right.shift
end
end
#Add the removed values to the array being rebuilt.
sorted_arr.concat(sorted_left).concat(sorted_right)
end
# Find the maximum
def maximum(arr)
mergesort(arr).last
end
def minimum(arr)
mergesort(arr).first
end
# expect it to return 42 below
result = maximum([2, 42, 22, 02])
puts "1. max of 2, 42, 22, 02 is: #{result}"
# expect it to return 2 below
result = minimum([2, 42, 22, 02])
puts "2. min of 2, 42, 22, 02 is: #{result}"
# expect it to return nil when empty array is passed in
result = maximum([])
puts "3. max on empty set is: #{result.inspect}"
result = minimum([])
puts "4. min on empty set is: #{result.inspect}"
result = mergesort([1, 10, 5, 78, 2, 39, 29, 55])
puts "5. mergesort of [1, 10, 5, 78, 2, 39, 29, 55] is: #{result}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment