Esempio n. 1
0
unsigned int BinaryHeap::insert(const unsigned int item, const int key) {
	_items.push_back(HeapItem(item, key, _binaryHeap.size()));
	_binaryHeap.push_back(_items.size() - 1);
	HeapItem &result = _items.at(_binaryHeap.back());
	this->_siftUp(result);
	return _items.size() - 1;
}
	// Helper function that searches the tree    
	void search(Node* node, const T& target, int k, std::priority_queue<HeapItem>& heap)
	{
		if(node == NULL) return;     // indicates that we're done here

		// Compute distance between target and current node
		ScalarType dist = distance(_items[node->index], target);

		// If current node within radius tau
		if(dist < _tau) {
			if(heap.size() == static_cast<size_t>(k)) heap.pop(); // remove furthest node from result list (if we already have k results)
			heap.push(HeapItem(node->index, dist));           // add current node to result list
			if(heap.size() == static_cast<size_t>(k)) _tau = heap.top().dist;     // update value of tau (farthest point in result list)
		}

		// Return if we arrived at a leaf
		if(node->left == NULL && node->right == NULL) {
			return;
		}

		// If the target lies within the radius of ball
		if(dist < node->threshold) {
			if(dist - _tau <= node->threshold) {         // if there can still be neighbors inside the ball, recursively search left child first
				search(node->left, target, k, heap);
			}

			if(dist + _tau >= node->threshold) {         // if there can still be neighbors outside the ball, recursively search right child
				search(node->right, target, k, heap);
			}

			// If the target lies outsize the radius of the ball
		} else {
			if(dist + _tau >= node->threshold) {         // if there can still be neighbors outside the ball, recursively search right child first
				search(node->right, target, k, heap);
			}

			if (dist - _tau <= node->threshold) {         // if there can still be neighbors inside the ball, recursively search left child
				search(node->left, target, k, heap);
			}
		}
	}