Skip to content

Instantly share code, notes, and snippets.

@zachpendleton
Created May 21, 2015 20:14
Show Gist options
  • Save zachpendleton/cc0f28c8001865132606 to your computer and use it in GitHub Desktop.
Save zachpendleton/cc0f28c8001865132606 to your computer and use it in GitHub Desktop.
Node = Struct.new(:value, :left, :right)
class KDTree
attr_reader :root
# points - an array of arrays containing x,y coordinates (e.g. [[1,1], [5,1]])
def initialize(points)
@root = init_tree(points.clone)
end
def init_tree(points)
axis = points.length % 2
points = points.sort_by { |point| point[axis] }
median = points.length / 2
if median == 0
return Node.new(points[median], nil, nil)
end
Node.new(points[median],
init_tree(points[0..median - 1]),
init_tree(points[median + 1..-1]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment