Created
May 21, 2015 20:14
-
-
Save zachpendleton/cc0f28c8001865132606 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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