Skip to content

Instantly share code, notes, and snippets.

@joshuastr
Created April 27, 2016 01:23
Show Gist options
  • Save joshuastr/7f8ab2e78eb17f9b6df3780107c0b371 to your computer and use it in GitHub Desktop.
Save joshuastr/7f8ab2e78eb17f9b6df3780107c0b371 to your computer and use it in GitHub Desktop.
# Sort the array from lowest to highest
def bubble_sort(array)
n = array.length
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
array
end
# expect it to return 42 below
result = bubble_sort([2, 42, 22, 02])
puts "max of 2, 42, 22, 02 is: #{result}"
# expect it to return 2 below
result = bubble_sort([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 = bubble_sort([])
puts "max on empty set is: #{result.inspect}"
result = bubble_sort([])
puts "min on empty set is: #{result.inspect}"
result = bubble_sort([-23, 0, -3])
puts "max of -23, 0, -3 is: #{result}"
result = bubble_sort([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