Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
m (Lang tags) |
m (→{{header|Ruby}}: formatting) |
||
Line 815: | Line 815: | ||
Although the native Ruby sort method for Arrays if much faster (O(n*log(n)) versus O(n**2)), you can find a Ruby version of Bubble sort hereunder. It adds the bubblesort! method to the Array object. Below are two different methods that show four different iterating constructs in ruby. |
Although the native Ruby sort method for Arrays if much faster (O(n*log(n)) versus O(n**2)), you can find a Ruby version of Bubble sort hereunder. It adds the bubblesort! method to the Array object. Below are two different methods that show four different iterating constructs in ruby. |
||
<lang ruby> |
<lang ruby> class Array |
||
class Array |
|||
def bubblesort1! |
def bubblesort1! |
||
length.times do |j| |
length.times do |j| |
||
Line 825: | Line 824: | ||
end |
end |
||
end |
end |
||
self |
|||
return self |
|||
end |
end |
||
</lang> |
|||
<lang ruby> |
|||
def bubblesort2! |
def bubblesort2! |
||
each_index do |index| |
each_index do |index| |
||
Line 837: | Line 834: | ||
end |
end |
||
end |
end |
||
self |
|||
return self |
|||
end |
end |
||
end |
end |
||
</lang> |
|||
ary = [3, 78, 4, 23, 6, 8, 6] |
|||
<lang ruby> |
|||
ary.bubblesort1! |
|||
p ary |
|||
# => [3, 4, 6, 6, 8, 23, 78] |
# => [3, 4, 6, 6, 8, 23, 78] |
||
</lang> |
</lang> |