Skip to content

Instantly share code, notes, and snippets.

@kaiguogit
Forked from davidvandusen/sort.rb
Last active July 20, 2016 18:29
Show Gist options
  • Save kaiguogit/5fda3d4e9d28b2dae3d0872cff678b30 to your computer and use it in GitHub Desktop.
Save kaiguogit/5fda3d4e9d28b2dae3d0872cff678b30 to your computer and use it in GitHub Desktop.
require 'benchmark'
# Sort the array from lowest to highest
def sort(arr)
#bubble sort
return arr if arr.length <= 1
sorted = true
while sorted
sorted = false
(arr.length-1).times do |i|
if arr[i] > arr[i+1]
arr[i], arr[i+1] = arr[i+1], arr[i]
sorted = true
end
end
end
arr
end
# Find the maximum
def maximum(arr)
puts "Bubble sort time #{Benchmark.measure{sort(arr).last}}"
puts "Build-in sort time #{Benchmark.measure{arr.sort.last}}"
sort(arr).last
end
def minimum(arr)
puts "Bubble sort time #{Benchmark.measure{sort(arr).first}}"
puts "Build-in sort time #{Benchmark.measure{arr.sort.first}}"
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