Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement