Skip to content

Instantly share code, notes, and snippets.

@McTano
Forked from davidvandusen/sort.rb
Last active May 25, 2016 03:26
Show Gist options
  • Save McTano/09542d2bff90c9b379cb70068ec9e4b0 to your computer and use it in GitHub Desktop.
Save McTano/09542d2bff90c9b379cb70068ec9e4b0 to your computer and use it in GitHub Desktop.
# Sort the array from lowest to highest
def sort(arr)
arr.sort
end
def swap(arr, x, y)
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
end
def bubble_sort(arr)
j = arr.length - 1
loop do
i = 0
swapped = false
while i < j
if arr[i] > arr[i + 1]
swap(arr, i, i + 1)
swapped = true
end
i += 1
end
j -= 1
return arr if swapped == false
end
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