#include <stdio.h>
#include <stdlib.h>

FILE *Arq;

/** Alternativa 1: usando typedef e struct 

typedef struct {
    float X;
    float Y;
} tipo_coord;

tipo_coord *Vetor;

**/

/** Alternativa 2: usando 2 vetores alocados dinamicamente */

float *VetorX;
float *VetorY;

troca(x1,y1,x2,y2)
float *x1,*y1,*x2,*y2;
{
  float temp;
  
  temp=*x1;
  *x1=*x2;
  *x2=temp;
  temp=*y1;
  *y1=*y2;
  *y2=temp;  
}

main()
{
   int trocou;
   int qtde;
   int i;
   
   Arq=fopen("dados.txt","rt");
   if (Arq == NULL)
   {
       printf("\n## Erro na abertura do arquivo ##\n");
       system("pause");
       exit(0);
   }   
   
   fscanf(Arq,"%d",&qtde);

   /** Alternativa 1: usando typedef e struct 
   Vetor=(tipo_coord *)calloc(qtde,sizeof(tipo_coord));
   **/
    
   VetorX=(float *)calloc(qtde,sizeof(float));
   VetorY=(float *)calloc(qtde,sizeof(float));
   
   for (i=0; i < qtde; i++)
     fscanf(Arq,"%f %f",&(VetorX[i]),&(VetorY[i]));
     
   /** VetorX acessado como ponteiros...
     fscanf(Arq,"%f %f",VetorX+i,VetorY+i);
   **/
     
   printf("Quantidade de dados Lidos: %d\n",qtde);
   for (i=0; i < qtde; i++)
     printf("%.2f %.2f\n", VetorX[i], VetorY[i]);
     
   printf("\n");
   printf("Ordenando...\n");
   
   while (1)
   {
     trocou=0;
     for (i=0; i< qtde-1; i++)
     {
         if (VetorX[i] > VetorX[i+1])
         {
             troca(&VetorX[i],&VetorY[i],&VetorX[i+1],&VetorY[i+1]);
             trocou=1;
         }             
         else
         if ((VetorX[i] == VetorX[i+1]) && 
             (VetorY[i] >  VetorY[i+1]))
         {
             troca(&VetorX[i],&VetorY[i],&VetorX[i+1],&VetorY[i+1]);
             trocou=1;
         }
     }
     if (!trocou) break;
   }             
        
   printf("Dados Ordenados: %d\n",qtde);
   for (i=0; i < qtde; i++)
     printf("%.2f %.2f\n", VetorX[i], VetorY[i]);
     
   printf("\n");
   printf("Primeiro: %.2f %.2f\n", VetorX[0], VetorY[0]);
   printf("Ultimo  : %.2f %.2f\n", VetorX[qtde-1], VetorY[qtde-1]);
   printf("Media   : %.2f %.2f\n", 
          (VetorX[0]+VetorX[qtde-1])/2.0, 
          (VetorY[0]+VetorY[qtde-1])/2.0);
   printf("Do meio : %.2f %.2f\n", VetorX[(int)((qtde-1)/2)], 
                                   VetorY[(int)((qtde-1)/2)]);
       
   printf("\n");
   system("pause");   
}
