在Python編程語言實現的kd樹的算法構建如下(從http://en.wikipedia.org/wiki/K-d_tree):kd樹籌建排序優化
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
則排序基於每一步進行。如何減少排序的數量?
你的意思是減少排序的數量? –
你必須對每一步排序數組,複雜度快速排序nlog(n)=>複雜度樹構建k * nlog(n),其中k - 步數;我想要優化算法樹build – Fandorin
k是數字維度,而不是步驟 – Scholle