Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sort the arr from lowest to highest
- def mergesort(arr)
- return arr if arr.size <= 1
- middle = arr.size / 2
- left = arr[0, middle]
- right = arr[middle, arr.size]
- merge(mergesort(left), mergesort(right))
- end
- def merge(left, right)
- sorted = []
- until left.empty? || right.empty?
- if left.first <= right.first
- sorted << left.shift
- else
- sorted << right.shift
- end
- end
- sorted + left + 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 "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 arr 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}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement