Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find closest double in unsorted array

I have a set of points in discrete space and coordinates are given as N double[] arrays.

Such as:

Point T1 = {1.3,2.5,4-3} ---> double[] x = {1.3}, double[] y = {2.5}, double[] z = {4.3}

Then I have a function which generates an offset from a given point in all directions in continuous space and I need to find closest match in my matrix/double array.

The problem is that I cannot sort these arrays and apply binary search, because components of Point will most likely not have the same indexes after sort, with respect to each other.

Is there some data structure/algorithm which I could apply to avoid iterative searching for the closest matching point?

Would it be better to organize points such that there is one array instance describing entire point rather than array per component ?

Edit

It looks like the ideal solution would utilize k-d trees as suggested in comment. Computer science algorithms are not my domain and therefore an answer demonstrating minimal example with k-d trees, or some alternative, would be most helpful while I am researching the topic.

like image 299
John Avatar asked Nov 10 '22 11:11

John


1 Answers

If I understand your problem, you have N arrays of size M of floats, each one containing the coordinate of a point along an axis in an N - dimensional space. You also have a single float, and you want to find the index of the point for which the float is closest to one of the components. If that's correct I would create a single array whose elements are pairs (value, index), with value being one of the components, and index bring the index of the point the component belongs to. You can then sort the array using value as the sorting.key. at that point you can use a binary search using the float.

Of course building and sorting the array makes sense only if you have multiple floats to search for, as sorting will take O (K log K), with K= N*M, and searching after that will take O (log K). If you only have to search for one float, you might as well do a full search on the array, which will be O (K).

like image 116
Roberto Attias Avatar answered Nov 15 '22 08:11

Roberto Attias