I have a problem with visualising polygon on google earth. I'm reading .xlsx file from the top to the bottom (in java) and I have a set of coordinates (x,y). My app is producing .kml file using JAK lib. After that when I import this .kml file into google earth I have wrong polygon shapes. Here is the example:

The thing is that in kml file coordinates are in the sequence as they appear on the image. Last coordinate is by default connected to the first one and this is the problem. How can I sort the coordinates that this shape will be a rectagle? Of course this is the simplest example. I have much more complicated polygons (in the file) than the rectangle one.