I'm working on a vector map editor and I have a set of elements, each of which specifies its bounding box within the view. As the mouse moves I want to highlight the first element whose bounding box contains the current mouse location. Right now I use a simple list and go through it, but as the number of elements is likely to increase, the O(n) complexity of the current search algorithm will be problematic for an interactive application.
What would be a better algorithm/data structure for this?
Some additional constraints/requirements:
After browsing through books, I've found one answer in Computational Geometry book (p. 237 in 3rd edition; 2008). This type of search is often referred to as stabbing query and is usually implemented using segment trees.
Complexities:
If you sort your elements by lower x-location, you can skip all elements before a certain point. If you have a second list with upper x-location, you know when you're done.
Another idea: Create a grid maybe splitting the whole area into 100x100 parts. Now find once out, in which parts of your grid a figure is overlapping:
5
4
3 xx
2 xxxx
1 xx
0
0 1 2 3 4 5
For this figure it would be (1,1),(1,2)(2,2)(2,3) A map of x*y Lists would now contain this shape s for the 4 locations (1,1)->s, (1,2)->s, ...
If you have seldom insertions/deletions, but often comparisions, this would speed your searches up. You would only visit the shapes, associated to a certain cell, and investigate the exact coordinates for these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With