I have created this simple BST in Ruby:
class Node
attr_accessor :data, :left, :right
def initialize data
@data = data
end
end
def insert root, data
current = root
loop do
node = current.data < data ? current.right : current.left
break if node.nil?
current = node
end
if current.data < data
current.right = Node.new(data)
else
current.left = Node.new(data)
end
end
Note: I don't use recursion because I get a "stack too deep" exception when the BST becomes large.
Then I try to insert about 6M records:
root = Node.new('root')
insert root, "something"
insert root, "another"
# ...
It takes about 30 minutes to complete on my MacOS, which seems really too much!
Why it takes so long (with SQLite I can index in 30 seconds the same data)?
Can you suggest any optimization to the above code?