You are looking for kd-tree range search or range query.
- Quadtrees (or octtrees or 16-trees...) are better when there is a changing set of points, but you expect the distribution to be uniform. No further balancing steps are needed, because the structure of the tree is fixed.
- kd-trees perform better on a fixed set of point, even with non-uniform distribution. When the point set changes, it is hard (but not impossible) to do self-balancing steps.
- AABB trees (or fat AABB trees) provide a fast way for testing overlapping shapes, not only points. AABB trees need some balancing occasionally. When constantly moving objects are included, common way is to use "fat AABB-s", so you don't have to update the tree in every frame.
- Sorting by only one axis and using binary search (something like abelenky suggested, but I think there is no point in doing a second binary search) is a simple and elegant solution, but will be slow when for example you sort by the X axis, and all the points are on a line parallel with Y. You have to do a linear filtering on the points which are matched by the binary searches by X. Time complexity is worst case
O(n)
, but this worst case happens pretty often.
All these algorithms run queries in average O(log n + k)
where k is the count of matched points.
Gridding, like Yves suggested, can perform range search in O(k)
time, but only when the size of the query rectangle is bounded. This is what they often do in particle simulations. Gridding can be used even when the input set is not bounded -- just make a fixed count of buckets based on hash of the grid coordinates. But if the query rectangle can be of arbitrary size, then gridding is a no-go.