Skip to content

Instantly share code, notes, and snippets.

@hyjk2000
Last active August 18, 2016 06:43
Show Gist options
  • Select an option

  • Save hyjk2000/30fe844769fa895c53745085432c2d81 to your computer and use it in GitHub Desktop.

Select an option

Save hyjk2000/30fe844769fa895c53745085432c2d81 to your computer and use it in GitHub Desktop.
Compare Bubble Sort and Quick Sort
def random_array(size)
Array.new(size) { rand(size) }
end
def bubble_sort(array)
array.size.times do
array[0..-2].each_index do |i|
array[i], array[i + 1] = array[i + 1], array[i] if array[i] > array[i + 1]
end
end
array
end
def quick_sort(array)
return array if array.size < 2
left, right = array[1..-1].partition { |y| y <= array.first }
quick_sort(left) + [array.first] + quick_sort(right)
end
require 'benchmark'
array = random_array(5000)
Benchmark.bmbm do |x|
x.report('bubble_sort') { bubble_sort(array) }
x.report('quick_sort') { quick_sort(array) }
x.report('sort') { array.sort }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment