Jump to content

Sorting algorithms/Bubble sort: Difference between revisions

m
m (Lang tags)
m (→‎{{header|Ruby}}: formatting)
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.
 
<lang ruby> class Array
class Array
def bubblesort1!
length.times do |j|
Line 825 ⟶ 824:
end
end
self
return self
end
 
</lang>
<lang ruby>
def bubblesort2!
each_index do |index|
Line 837 ⟶ 834:
end
end
self
return self
end
end
 
</lang>
ary = [3, 78, 4, 23, 6, 8, 6]
<lang ruby>
puts [3, 78, 4, 23, 6, 8, 6]ary.bubblesort1!
p ary
# => [3, 4, 6, 6, 8, 23, 78]
</lang>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.