Skip to content

Instantly share code, notes, and snippets.

@gingeleski
Created January 26, 2015 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gingeleski/84b49fdefaa734e86aa1 to your computer and use it in GitHub Desktop.
Save gingeleski/84b49fdefaa734e86aa1 to your computer and use it in GitHub Desktop.
Simple bubble sort for numbers.
# Simple bubble sort for numbers
def bubble_sort(array_to_sort)
swap = true # Track whether swap has occurred
while swap
(0... array_to_sort.length - 1).each do |x|
# If we detect disorder...
if array_to_sort[x] > array_to_sort[x + 1]
# Perform a simple 3-step swap
temp = array_to_sort[x + 1]
array_to_sort[x + 1] = array_to_sort[x]
array_to_sort[x] = temp
swap = true
end
end
end
return array_to_sort # At this point it's sorted
end
# EXAMPLE
bubble_sort([1,3,5,2,4])
# [1,2,3,4,5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment