Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
Line 113: | Line 113: | ||
This sort is actually a C quicksort. |
This sort is actually a C quicksort. |
||
Although the native Ruby sort method for Arrays if much faster, you can find a Ruby version of Bubble sort hereunder. It adds the sort! method to the Array object, making it readily available for all Array objects |
|||
Bubble sort algorithm |
|||
class Array |
|||
def sort! |
|||
(length-1).downto(0) do |nrSwaps| |
|||
nrSwaps.times do |ix| |
|||
self[ix],self[ix+1]=self[ix+1],self[ix] if self[ix]>self[ix+1] |
|||
end |
|||
end |
|||
return self |
|||
end |
|||
end |
|||
ary = [5,4,2,3,1] |
|||
puts ary.sort! |