Last active
August 29, 2015 14:20
-
-
Save laurenachoo/c0977b8717a2b69f00e7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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) | |
| #is storing all the parts of the array | |
| n = arr.length | |
| arr_copy = arr.clone | |
| #this will keep looping this code until it cannot swap anymore | |
| loop do | |
| swapped = false | |
| (n-1).times do |i| | |
| if arr_copy[i] > arr_copy[i + 1] | |
| #it's switching these two, ,to put the greater one in front | |
| arr_copy[i], arr_copy[i+1] = arr_copy[i+1], arr_copy[i] | |
| swapped = true | |
| end | |
| end | |
| break if not swapped | |
| end | |
| arr_copy | |
| 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