I've got a large array of coordinates (a struct containing x and y, among other things) and for each pair of coordinates, I'm trying to find another pair that's closest to it from that array.

int i, j, d = 0, cd = 0, closest;
  closest = 0;
    if (i != j){
      //find distance bewteen i and j
      cd = sqrt(pow(coords[i].x-coords[j].x,2)+pow(coords[i].y-coords[j].y,2))
      if(cd < d){
        d = cd;
        closest = j;
  //do stuff with the 'closest' variable

The problem is, this code runs really slowly, as it has to execute size^2 times, and I'm constantly running this code because the x and y coordinates are always changing.

Is there a faster way to do what I'm trying to do? I know that I could potentially cut calculation time by 2, because if a is closest to b, then b is closest to a, but beyond that, I can't think of any optimizations.

Edited by AndrewYY: n/a

7 Years
Discussion Span
Last Post by firstPerson
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.