Skip to main content
1 of 4
sam hocevar
  • 23.9k
  • 2
  • 64
  • 95

Your question is not precise enough. An array of points is only « clockwise » or « anti-clockwise » relative to a reference point. Otherwise, any array of three points can always be either CW or CCW. In your case, I believe using the barycenter of the points as a reference point is reasonable.

A good method for an unknown number of points could be the following one:

  • let P[0], P[1], ... P[n-1] be the list of points to sort
  • let M be the barycenter of all points
  • compute a[0], a[1], ... a[n-1] such as a[i] = atan2(P[i].y - M.y, P[i].x - M.x);
  • sort points relative to their a value, using qsort for instance.

However, you can be sure that a good sorting algorithm will perform poorly with three input values compared to an ad-hoc method. Using atan2 is still valid, but just don't use qsort.

sam hocevar
  • 23.9k
  • 2
  • 64
  • 95