Created
January 26, 2015 00:25
-
-
Save gingeleski/84b49fdefaa734e86aa1 to your computer and use it in GitHub Desktop.
Simple bubble sort for numbers.
This file contains 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
# 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