/*************************************************
 ** This program reads in points from the user and
 ** prints them back out in sorted order from
 ** closest to the origin to farthest.
 *************************************************/
#include <iostream>
using namespace std;

/*************************************************
 ** PROTOTYPES
 *************************************************/
void selectionsort(double **A, int N);

/*************************************************
 ** MAIN
 *************************************************/
int main()
{
  // Get number of points and create & read array
  int n;
  cout << "How many points? ";
  cin >> n;
  cout << "Enter points (x,y,z): ";
  double **A = new double*[n];
  for(int i = 0; i < n; i++)
  {
    A[i] = new double[3];
    char c;
    cin >> c >> A[i][0] 
	>> c >> A[i][1] 
	>> c >> A[i][2] >> c;
  }

  // Sort points!
  selectionsort(A,n);

  // Print out points
  for(int i = 0; i < n; i++)
  {
    cout << '(' << A[i][0] 
	 << ',' << A[i][1] 
	 << ',' << A[i][2] << ") ";
  }
  cout << endl;
  return 0;
}

/*************************************************
 ** DEFINITIONS
 *************************************************/
bool before(double *a, double *b) 
{ 
  return sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]) 
         < 
         sqrt(b[0]*b[0] + b[1]*b[1] + b[2]*b[2]); 
}

void selectionsort(double **A, int N)
{
  for(int length = N; length > 1; length--)
    {
      // Find imax, the index of the largest
      int imax = 0, i;
      for(i = 1; i < length; i++)
	if (before(A[imax],A[i]))
	  imax = i;
      // Swap A[imax] & the last element
      double *temp = A[imax];
      A[imax] = A[length - 1];
      A[length - 1] = temp;
    }
}