Created
April 27, 2016 02:06
-
-
Save charmainetham/9867558a3d9903e288c20a49b108c6ff to your computer and use it in GitHub Desktop.
merge sort
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
# Sort the array from lowest to highest | |
def sort(arr) | |
# if the size of array is less than or 1 output that item | |
arrlen = arr.length | |
if arrlen <= 1 | |
return arr | |
else | |
mid = arrlen/2 #finding the middle of the array | |
leftarr = arr[0..mid-1]#splitting it into the first half of the array | |
rightarr = arr[mid ..arrlen]#splitting it to second half of array up to the last index of the array | |
merge(leftarr, rightarr) | |
end | |
end | |
#we had to create a second method here to merge the arrays after we go through the loop | |
def merge(leftarr, rightarr) | |
if leftarr.empty? | |
return rightarr | |
elsif rightarr.empty? | |
return leftarr | |
elsif leftarr.first < rightarr.first | |
leftarr[0..1-1] + merge(leftarr[1..leftarr.length], rightarr) | |
else | |
rightarr[0..1-1] + merge(leftarr, rightarr[1..rightarr.length]) | |
end | |
end | |
# Find the maximum | |
def maximum(arr) | |
sort(arr).last | |
end | |
def minimum(arr) | |
sort(arr).first | |
end | |
# expect it to return 42 below | |
result = maximum([2, 42, 22, 02]) | |
puts "max of 2, 42, 22, 02 is: #{result}" | |
# expect it to return 2 below | |
result = minimum([2, 42, 22, 02]) | |
puts "min of 2, 42, 22, 02 is: #{result}" | |
# expect it to return nil when empty array is passed in | |
result = maximum([]) | |
puts "max on empty set is: #{result.inspect}" | |
result = minimum([]) | |
puts "min on empty set is: #{result.inspect}" | |
result = maximum([-23, 0, -3]) | |
puts "max of -23, 0, -3 is: #{result}" | |
result = maximum([6]) | |
puts "max of just 6 is: #{result}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment