Skip to content

Instantly share code, notes, and snippets.

@theHamdiz
Created July 25, 2015 20:36
Show Gist options
  • Select an option

  • Save theHamdiz/550da2c9386a39b5907d to your computer and use it in GitHub Desktop.

Select an option

Save theHamdiz/550da2c9386a39b5907d to your computer and use it in GitHub Desktop.
Bubble sort simple sorting algorithm
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