Sort points from closest to farthest

314 Views Asked by At

Is there an algorithm that given the set of points: p1(10,-4) p2(8,3) p3(6,-4) and p4(5,1) returns you the sequence to follow from the closest point to the furthest one changing every time your starting point? I mean, in my example I start from p0(7,0), so I want a sorting algorithm that returns me p4,p2,p1,p3 because when selecting p4 as the closest point to p0, my starting point becomes p4. Then I select p2, which is the closest to p4, then p1, ehich is the closest to p4 and finally p3, which is the closest to p1. The algorithm must run in O(nlogn)

1

There are 1 best solutions below

0
On

That sounds like a minimum spanning tree, try using Prim's algorithm and storing the order of addition in a list you would get that sorting.

Check out this very cool animation from wikipedia

enter image description here

Complexity depends on the chosen priority queue.