Skip to content

Instantly share code, notes, and snippets.

@vsevolod
Created April 16, 2018 14:36
Show Gist options
  • Save vsevolod/c9022291f823f5c1a9e6317679b077b8 to your computer and use it in GitHub Desktop.
Save vsevolod/c9022291f823f5c1a9e6317679b077b8 to your computer and use it in GitHub Desktop.
Bubble sorting
class BubbleArray < Array
def sort
dup.sort!
end
def sort!
return self if self.size <= 1
for i in 0...size
swapped = false
for j in (i+1)...size
if (self[i] <=> self[j]) > 0
swap(i, j)
swapped = true
end
end
return self unless swapped
end
end
private
def swap(i, j)
self[i], self[j] = self[j], self[i]
end
end
def assert(object, value)
if object == value
print '.'
else
puts "Error: #{object.inspect} != #{value}"
end
end
array = BubbleArray[10, 32, 22, 90, 0, -9, 24, 88, 92, 35, 90, 8, 99, 100]
assert(array.sort, [-9, 0, 8, 10, 22, 24, 32, 35, 88, 90, 90, 92, 99, 100])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment