Skip to content

Instantly share code, notes, and snippets.

@charmainetham
Created April 27, 2016 03:01
Show Gist options
  • Save charmainetham/89c83bb7923da49c376a2623d1382b72 to your computer and use it in GitHub Desktop.
Save charmainetham/89c83bb7923da49c376a2623d1382b72 to your computer and use it in GitHub Desktop.
bubblesort
# Sort the array from lowest to highest
def sort(arr)
swap = false
until swap
swap = true
(arr.length - 1).times do |x|
if arr[x] > arr[x +1]
arr[x], arr[x+1] = arr[x+1], arr[x]
swap = false
end
end
end
arr
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