Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. # The bubble sort algorithm:
  2. # Compare adjacent elements. If the first is greater than the second, swap them.
  3.  
  4. # Do this for each pair of adjacent elements, starting with the first two and ending
  5. # with the last two. At this point the last element should be the greatest.
  6.  
  7. # Repeat the steps for all elements except the last one.
  8.  
  9. # Continue for one less element each time, until there are no more pairs to compare.
  10.  
  11. a = (1..10).to_a.shuffle
  12.  
  13. puts a.inspect
  14. count = a.length - 1
  15.  
  16. sorted = false
  17.  
  18. until sorted
  19. sorted = true
  20.  
  21. a.each_index do |i|
  22. next unless i < a.length - 1
  23. if a[i] > a[i+1]
  24. a[i], a[i+1] = a[i+1], a[i]
  25. sorted = false
  26. end
  27. end
  28. end
  29.  
  30. puts a.inspect
  31.  
  32. # returns the sorted array
  33. def bubble_sort(array)
  34. swapped = false
  35.  
  36. array.each_index do |index|
  37. next unless index < array.length - 1 # we can't look ahead when we're at the last index
  38.  
  39. if array[index] > array[index + 1]
  40. array[index], array[index + 1] = array[index + 1], array[index]
  41. swapped = true
  42. end
  43. end
  44.  
  45. if swapped
  46. bubble_sort(array)
  47. else
  48. array
  49. end
  50. end
  51.  
  52. a.shuffle!
  53.  
  54. puts a.inspect
  55.  
  56. puts bubble_sort(a).inspect
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement