kd树构建排序优化

时间:2012-09-19 12:17:24

标签: python kdtree

用Python编程语言实现的kd-tree的算法构建如下(来自http://en.wikipedia.org/wiki/K-d_tree):

class Node: pass

def kdtree(point_list, depth=0):

  if not point_list:
    return None

  # Select axis based on depth so that axis cycles through all valid values
  k = len(point_list[0]) # assumes all points have the same dimension
  axis = depth % k

  # Sort point list and choose median as pivot element
  point_list.sort(key=lambda point: point[axis])
  median = len(point_list) // 2 # choose median

  # Create node and construct subtrees
  node = Node()
  node.location = point_list[median]
  node.left_child = kdtree(point_list[:median], depth + 1)
  node.right_child = kdtree(point_list[median + 1:], depth + 1)
  return node

每一步都要进行排序。如何减少排序量?

1 个答案:

答案 0 :(得分:1)

看起来你只是在分拣中位数。相反,您可以实现线性时间选择算法,例如quickselect,然后执行point_list的线性时间分区。然后,您根本不需要进行排序。