So let's say I have the points of this shape's outline:

Now, these points aren't sorted. What I want to do is turning [B, E, H, M, P, ...] into [A, B, C, D, E, ...].
I tried to find the top-left point (A) and then go from it on and on. I faled in cases like this one:

I don't want to use libraries like OpenCV, but write the algorithm myself. Any help?