Advertisement
Guest User

Untitled

a guest
May 24th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. # Sort the arr from lowest to highest
  2. def mergesort(arr)
  3. return arr if arr.size <= 1
  4. middle = arr.size / 2
  5. left = arr[0, middle]
  6. right = arr[middle, arr.size]
  7. merge(mergesort(left), mergesort(right))
  8. end
  9.  
  10. def merge(left, right)
  11. sorted = []
  12. until left.empty? || right.empty?
  13. if left.first <= right.first
  14. sorted << left.shift
  15. else
  16. sorted << right.shift
  17. end
  18. end
  19. sorted + left + right
  20. end
  21.  
  22. # Find the maximum
  23. def maximum(arr)
  24. mergesort(arr).last
  25. end
  26.  
  27. def minimum(arr)
  28. mergesort(arr).first
  29. end
  30.  
  31. # expect it to return 42 below
  32.  
  33. result = maximum([2, 42, 22, 02])
  34. puts "max of 2, 42, 22, 02 is: #{result}"
  35.  
  36. # expect it to return 2 below
  37. result = minimum([2, 42, 22, 02])
  38. puts "min of 2, 42, 22, 02 is: #{result}"
  39.  
  40. # expect it to return nil when empty arr is passed in
  41. result = maximum([])
  42. puts "max on empty set is: #{result.inspect}"
  43.  
  44. result = minimum([])
  45. puts "min on empty set is: #{result.inspect}"
  46.  
  47. result = maximum([-23, 0, -3])
  48. puts "max of -23, 0, -3 is: #{result}"
  49.  
  50. result = maximum([6])
  51. puts "max of just 6 is: #{result}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement