Last active
August 18, 2016 06:43
-
-
Save hyjk2000/30fe844769fa895c53745085432c2d81 to your computer and use it in GitHub Desktop.
Compare Bubble Sort and Quick Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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