Anonymous user
Sorting algorithms/Bubble sort: Difference between revisions
→[[Ruby]]
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.
class Array
def
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 bubblesort2!
a, b =
a, b = b, a if b < a
end▼
end
▲ end
return self
end▼
end
▲end
# => [3, 4, 6, 6, 8, 23, 78]▼
▲# => [3, 4, 6, 6, 8, 23, 78]
|