Given a set of distinct points in 2D space, and a rectangle (coordinates of all four points, sides parallel with xy axis) how can I quickly find which points are inside the rect
You could group point in sectors. If a sector is completely in or out of given rectangle then all point within it are also in or out. If a sector is partially in then you have to search O(n) for points in that sector to check if they are in the rectangle. Look for k-d tree search.
You are looking for kd-tree range search or range query.
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.
I think you should store your points in a quadtree. I have not worked out the details, but it should allow to basically do something similar to a binary search that directly yields the points that are inside an rectangle.
If your points are clustered, i.e. there exist clusters that contain many points in a small area and other areas that contain no, or very few points an R-tree might be even better.
Runtime complexity should be O(logN) I think.
Along with other answers, you can also look into Morton codes (z-order curve sorting).
In your case, that is static data, you can even represent the whole point data as an array.
https://en.wikipedia.org/wiki/Z-order_curve
This paper also have a rather complicated timeline of different "multi-dimentional access methods" --http://www.cc.gatech.edu/computing/Database/readinggroup/articles/p170-gaede.pdf
A classical answer is the kD-tree (2D-tree in this case).
For a simple alternative, if your points are spread uniformly enough, you can try by gridding.
Choose a cell size for a square grid (if the problem is anisotropic, use a rectangular grid). Assign every point to the grid cell that contains it, stored in a linked list. When you perform a query, find all cells that are overlapped by the rectangle and scan them to traverse their lists. For the partially covered cells, you will need to perform the point-in-rectangle test.
The choice of the size is important: too large can result in too many points needing to be tested anyway; too small can result in too many empty cells.