Skip to content

Instantly share code, notes, and snippets.

@RobertCam
Created September 30, 2015 00:33
Show Gist options
  • Save RobertCam/a22043ee01baf7eacf0d to your computer and use it in GitHub Desktop.
Save RobertCam/a22043ee01baf7eacf0d to your computer and use it in GitHub Desktop.
sort using bubblesort. Compare efficiency with array#sort method using benchmark
# Sort the array from lowest to highest
def bubblesort(arr)
n = arr.length
loop do
swapped = false
(n-1).times do |i|
if arr[i] > arr[i+1]
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = true
end
end
break if not swapped
end
arr
end
# Find the maximum
def maximum(arr)
bubblesort(arr).last
end
def minimum(arr)
bubblesort(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}"
require 'benchmark'
puts Benchmark.measure {bubblesort [2, 42, 22, 02]}
puts Benchmark.measure {[2, 42, 22, 02].sort}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment