Created
March 29, 2016 21:04
-
-
Save FioFiyo/8fefaa0a165631fde3733d04c903535d to your computer and use it in GitHub Desktop.
using anything other than sort type of methods to run through an array and scan the highest number.
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
# Find the maximum | |
#Scan the array to compare integers and find the maximum | |
#within that array if there are objects inside the array | |
#otherwise set it to nil. | |
def maximum(arr) | |
#arr.max | |
#create the sort option | |
#comparing the actual number not the index using arr[i] | |
itswaps = true | |
while itswaps do | |
itswaps = false | |
0.upto(arr.length-2) { |i| | |
if arr[i] > arr[i+1] | |
arr[i], arr[i+1] = arr[i+1], arr[i] | |
itswaps = true | |
end | |
} | |
end | |
arr.last | |
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