Skip to content

Instantly share code, notes, and snippets.

@shinobcrc
Forked from davidvandusen/sort.rb
Last active June 22, 2016 01:57
Show Gist options
  • Save shinobcrc/1d8691a028430d2a677b2d48aa2196c3 to your computer and use it in GitHub Desktop.
Save shinobcrc/1d8691a028430d2a677b2d48aa2196c3 to your computer and use it in GitHub Desktop.
# # Sort the array from lowest to highest
# def sort(arr)
# arr.sort
# end
def bubble_sort(array)
#n = total number of values in array
n = array.length
loop do
#iterate through the array to find the highest number
swapped = false
(n-1).times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
swapped = true
end
end
break if not swapped
end
array
end
# # Find the maximum
def maximum(arr)
bubble_sort(arr).last
end
def minimum(arr)
bubble_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