Created
July 25, 2015 20:36
-
-
Save theHamdiz/550da2c9386a39b5907d to your computer and use it in GitHub Desktop.
Bubble sort simple sorting algorithm
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 bubble_sort(array) | |
| n = array.length | |
| loop do | |
| swapped = false | |
| (n-1).times do |i| | |
| # if the item that comes first in the array is bigger than that comes next | |
| # then resort it | |
| if array[i] > array[i+1] | |
| array[i], array[i+1] = array[i+1], array[i] | |
| swapped = true | |
| end | |
| end | |
| break unless swapped | |
| end | |
| array | |
| end | |
| t = Time.now | |
| ar = (1..999).to_a.reverse | |
| p bubble_sort(ar) | |
| puts "Took #{Time.now - t} seconds" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment