Sorting algorithms/Bubble sort: Difference between revisions

Line 193:
This sort is actually a C quicksort.
 
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. ThereBelow are atwo coupledifferent ofmethods differentthat waysshow tofour different implementiterating thisconstructs in ruby.
 
class Array
def bubblesortbubblesort1!
for j inlength.times 0...lengthdo |j|
for i in 1...(length - j)
if self[i] < self[i - 1]
self[i], self[i - 1] = self[i - 1], self[i]
end
end
end
end
return self
end
 
 
def bubblesort!
def bubblesort2!
each_index do |index|
(length - 1).downto( index )each_index do |iindex|
a,(length b = self[i- 1],).downto( index ) do self[|i]|
a, b = bself[i-1], a if b < aself[i]
a, b = b, a if b < a
end
end
end
return self
end
end
end
 
ary = puts [3, 78, 4, 23, 6, 8, 6].bubblesort1!
# => [3, 4, 6, 6, 8, 23, 78]
puts ary.bubblesort!
# => [3, 4, 6, 6, 8, 23, 78]
Anonymous user