title: Sort points in clockwise order?
body: <p>Given an array of x,y points, how do I sort the points of this array in clockwise order (around their overall average center point)? My goal is to pass the points to a line-creation function to end up with something looking rather "solid", as convex as possible with no lines intersecting.</p>
  
  <p>For what it's worth, I'm using Lua, but any pseudocode would be appreciated.</p>
  
  <p><strong>Update:</strong> For reference, this is the Lua code based on Ciamej's excellent answer (ignore my "app" prefix):</p>
  
  <pre><code>function appSortPointsClockwise(points)
      local centerPoint = appGetCenterPointOfPoints(points)
      app.pointsCenterPoint = centerPoint
      table.sort(points, appGetIsLess)
      return points
  end
  
  function appGetIsLess(a, b)
      local center = app.pointsCenterPoint
  
      if a.x &gt;= 0 and b.x &lt; 0 then return true
      elseif a.x == 0 and b.x == 0 then return a.y &gt; b.y
      end
  
      local det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y)
      if det &lt; 0 then return true
      elseif det &gt; 0 then return false
      end
  
      local d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y)
      local d2 = (b.x - center.x) * (b.x - center.x) + (b.y - center.y) * (b.y - center.y)
      return d1 &gt; d2
  end
  
  function appGetCenterPointOfPoints(points)
      local pointsSum = {x = 0, y = 0}
      for i = 1, #points do pointsSum.x = pointsSum.x + points[i].x; pointsSum.y = pointsSum.y + points[i].y end
      return {x = pointsSum.x / #points, y = pointsSum.y / #points}
  end
  </code></pre>
  
  <p></p>