Abanoub_Ashraf's blog

By Abanoub_Ashraf, 4 years ago, In English

Angular Sorting

hello , my friends

This is my first blog and I want to share some knowledge that may help other to solve some problems and

if you have another algorithm you can explain it in comments .

Let's start , you are given n points . each point is at integer coordinates (x,y) . can you sort them in clockwise order and vice versa ?

the points are here like that

Think about it for a bit and then continue with me ...

if we have slope from each point and (0,0) ?

Nice , we can get angle with x-axis and from this we can sort them !!

we can see like this

let's calculate the angle

angle = atan2(y,x) — in redius .

angle = atan2(y,x) * 180 /PI — this is in degree .

but what about negative angles ?!

we can add 360 degree to be positive .

angle+=(angle<0)*360 .

code in C++ https://ideone.com/fork/MXtcfD

Problem related to this concept https://codeforces.me/gym/103562/problem/D

In the end, I hope this blog is useful and that you like it . I will be happy with your comment :)

Thank you

  • Vote: I like it
  • +9
  • Vote: I do not like it

| Write comment?
»
4 years ago, hide # |
 
Vote: I like it +18 Vote: I do not like it

C'mon man. You are a lgm. What a question?!

»
4 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Using complex and using arg function worked for me in a problem.

»
4 years ago, hide # |
 
Vote: I like it +2 Vote: I do not like it

using atan2 to sort is pretty cringe (and inaccurate), use the CCW function instead

»
4 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

ايوة يابيبو ياحلاااق

»
3 years ago, hide # |
← Rev. 2  
Vote: I like it 0 Vote: I do not like it

ATTENTION!

If the pint (0,0) is not in center of the points, it may give an error. see the following test case: 4 4 0 2 1 3 3 4 3

To solve this error, you may calculate the angles using the center point of all these points instead of (0,0). center point can be calculated using ((x1+x2+x3+...+xn)/n, (y1+y2+y3+...+yn)/n)