Four 2D points in an array. I need to sort them in clockwise order. I think it can be done with just one swap operation but I have not been able to put this down formally.
Edit: The four points are a convex polygon in my case.
Edit: The four points are the vertices of a convex polygon. They need not be in order.
if you just need to deal with 4 points then there is a most easy way of doing that
sort by y value
top row is the first two points, bottom row is the rest 2 points
for top and bottom row, sort them by x value
.
Work it out the long way then optimize it.
A more specific problem would be to sort the coordinates by decreasing angle relative to the positive x axis. This angle, in radians, will be given by this function:
Then, of course, it's just a matter of sorting the coordinates by angle. Note that arctan(w) > arctan(z) if and only if x > z, so you can optimize a function which compares angles to each other pretty easily.
Sorting such that the angle is monotonically decreasing over a window (or such that it increases at most once) is a bit different.
In lieu of a an extensive proof I'll mention that I verified that a single swap operation will sort 4 2D points in clockwise order. Determining which swap operation is necessary is the trick, of course.
I have one further improvement to add to my previous answer
remember - these are the cases we can be in.
If ABC is anticlockwise (has negative signed area) then we are in cases 3, 4, 6. If we swap B & C in this case, then we are left with the following possibilities:
Next we can check for ABD and swap B & D if it is anticlockwise (cases 5, 6)
Finally we need to check ACD and swap C & D if ACD is anticlockwise. Now we know our points are all in order.
This method is not as efficient as my previous method - this requires 3 checks every time, and more than one swap; but the code would be a lot simpler.
How about this?
Ideas?