5

Here's my problem:

I have a website where people can search based on their location (which is converted to lat/long coordinates). I have many products stored in a database with their lat/long coordinates. I also have a function to calculate the distance between two points based on their coordinates.

Now I'm looking for a way to find one of these things:

  • The n nearest products to the user's location.
  • All the products within a radius of x kilometers from the user's location.

Both solutions would be fine for my application.

Currently I just iterate over all the database entries, find their distance, and sort them. This obviously gets way too slow with a lot of entries.

Are there any algorithms/data structures I can apply here to make it faster?

Thanks in advance!

Wouter Florijn
  • 215
  • 1
  • 6

1 Answers1

2

Your problem (at least the second variant) is known as 2D range searching. Commonly used data structures are range trees and k-d trees. Searching for range searching on the web will open you a window into the area. These lecture notes come up, for example.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514