Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # The bubble sort algorithm:
- # Compare adjacent elements. If the first is greater than the second, swap them.
- # Do this for each pair of adjacent elements, starting with the first two and ending
- # with the last two. At this point the last element should be the greatest.
- # Repeat the steps for all elements except the last one.
- # Continue for one less element each time, until there are no more pairs to compare.
- a = (1..10).to_a.shuffle
- puts a.inspect
- count = a.length - 1
- sorted = false
- until sorted
- sorted = true
- a.each_index do |i|
- next unless i < a.length - 1
- if a[i] > a[i+1]
- a[i], a[i+1] = a[i+1], a[i]
- sorted = false
- end
- end
- end
- puts a.inspect
- # returns the sorted array
- def bubble_sort(array)
- swapped = false
- array.each_index do |index|
- next unless index < array.length - 1 # we can't look ahead when we're at the last index
- if array[index] > array[index + 1]
- array[index], array[index + 1] = array[index + 1], array[index]
- swapped = true
- end
- end
- if swapped
- bubble_sort(array)
- else
- array
- end
- end
- a.shuffle!
- puts a.inspect
- puts bubble_sort(a).inspect
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement