Advertisement
Guest User

Untitled

a guest
Jan 25th, 2015
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. # Simple bubble sort for numbers
  2.  
  3. def bubble_sort(array_to_sort)
  4. swap = true # Track whether swap has occurred
  5.  
  6. while swap
  7. (0... array_to_sort.length - 1).each do |x|
  8. # If we detect disorder...
  9. if array_to_sort[x] > array_to_sort[x + 1]
  10. # Perform a simple 3-step swap
  11. temp = array_to_sort[x + 1]
  12. array_to_sort[x + 1] = array_to_sort[x]
  13. array_to_sort[x] = temp
  14.  
  15. swap = true
  16. end
  17. end
  18. end
  19.  
  20. return array_to_sort # At this point it's sorted
  21. end
  22.  
  23. # EXAMPLE
  24. bubble_sort([1,3,5,2,4])
  25.  
  26. # [1,2,3,4,5]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement