## Sort lines, part of a closed shape

Question

I have an array of structures, each structure element holds the endpoints of lines in 3D space.

```
struct POINTS
{
float xStart;
float yStart;
float zStart;
float xEnd;
float yEnd;
float zEnd;
};
```

Combining these lines will create a closed shape. Unfortunately the lines are not in the correct order.

To make the lines in order, to create the closed loop, I think the line points should rearrange like:

- Take a line, say LINE-A.
Find the start point of another line, say LINE-X, whose start point is LINE-A's end point.

OR

- Find the End point of another line, say LINE-Y, whose End point is LINE-A's start point.....

However I am not sure this is the right solution. I will appreciate for suggesting suitable optimized methods to solve this problem.

**[Note Added]**
**My real intention is to create the closed shape in 2D plane. So solution for 2D plane is also expected from the geniuses.**

Show source

## Answers ( 1 )

Main idea - put all points to multimap (where key is a point coordinates and value is a index of line and begin/end mark). After that you need to select any point as startup, find index of line that has this point and fetch another end of line. Then you mark current line as used and use end of current line as startup for next iteration.

The complexity of the algorithm is O(N * logN). This algorithm doesn't required end-to-start sorted data.

You can find full source code with example generation here: http://ideone.com/TuzjMn