Created
June 21, 2016 22:47
-
-
Save Leejojo/3370ede9c8a38c2eb5c807a3ae99c7e1 to your computer and use it in GitHub Desktop.
Max Value
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
def maximum(arr) | |
n = arr.length | |
loop do | |
swapped = false | |
(n-1).times do |i| | |
if arr[i] > arr[i+1] | |
arr[i], arr[i+1] = arr[i+1], arr[i] | |
swapped = true | |
end | |
end | |
break if not swapped | |
end | |
arr.last | |
end | |
=begin | |
# Find the maximum | |
def maximum(arr) | |
arr.max | |
end | |
=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 nil when empty array is passed in | |
result = maximum([]) | |
puts "max 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