在KD树中搜索速度慢

时间:2011-02-27 17:54:28

标签: ios nearest-neighbor kdtree recursive-datastructures

我正在实施一个KD树来将地图分成群组。我一直在使用Wikipedia's KD-tree article作为参考。搜索返回正确的最近邻点,但它比我预期的要慢。这是我的代码:

- (FDRKDTree *)nnSearchForPoint:(id <MKAnnotation>)point best:(FDRKDTree *)best {
// consider the current node
distToPoint = [self distanceBetweenAnnotations:self.location and:point];
if (distToPoint < best.distToPoint) {
    best = self;
}
// search near branch
int axis = depth % 2;
FDRKDTree *child = nil;
if (axis) {
    if (point.coordinate.latitude > location.coordinate.latitude)
        child = rightChild;
    else
        child = leftChild;
} else {
    if (point.coordinate.longitude > location.coordinate.longitude)
        child = rightChild;
    else
        child = leftChild;
}
if (child != nil)
    best = [child nnSearchForPoint:point best:best];

child = nil;
//search the away branch - maybe
if (axis) {
    if (fabs(point.coordinate.latitude - self.location.coordinate.latitude) <
        best.distToPoint) {
        if (point.coordinate.latitude > location.coordinate.latitude)
            child = leftChild;
        else
            child = rightChild;
    }
} else {
    if (fabs(point.coordinate.longitude - self.location.coordinate.longitude) <
        best.distToPoint) {
        if (point.coordinate.longitude > location.coordinate.longitude)
            child = leftChild;
        else
            child = rightChild;
    } 
}


if (child != nil) {
    best = [child nnSearchForPoint:point best:best];
}

return best;
}

我的问题是,如果我解释“一个简单的比较,看看搜索点和当前节点的分裂坐标之间的差异是否小于从搜索点到当前最佳点的距离(整体坐标) “是正确的。我将此解释为:

if (fabs(point.coordinate.latitude - self.location.coordinate.latitude) < best.distToPoint)

if (fabs(point.coordinate.longitude - self.location.coordinate.longitude) < best.distToPoint)

分别。任何其他建议也是受欢迎的。

感谢。

1 个答案:

答案 0 :(得分:0)

假设您的distToPointsqrt((x1-x0)**2+(y1-y0)**2),您所做的一切对我来说非常好。我在Python中实现了这个算法,这可能有助于交叉检查你的版本并澄清一些维基百科的文章要点: https://gist.github.com/863301