// ic210 sec 4002 //6 nov 2009 // read, sort, and print //an array of "points" by "magnitude" // each "point" is an array with 3 elements // "magnitude" of (a,b,c) is a^2+b^2+c^2 #include #include #include #include using namespace std; int maxIndex(double* *array, int size); void selectionSort(double* *arrayIn, int sizeIn); void swap(double*& a, double*& b); int search(double* value, double** arrayIn, int size); bool isBefore(double*, double*); //point functions double* readPoint(istream &in); void writePoint(double *point, ostream &out); double magnitude(double *point); int main() { ifstream fin("class28_data.txt"); if (!fin) { cout << "Error" << endl; exit(1); } // create array and initialize with values int size ; fin >> size; double** array = new double*[size]; for (int i = 0; i < size; i++) { array[i] = readPoint(fin); } // sort the array selectionSort(array, size); // display the array for (int j = 0; j < size; j++) { writePoint(array[j],cout); cout << endl; } return 0; } // Returns the index of the maximum element in the array int maxIndex(double* *array, int size) { int maxIndex = 0; //int maxValue = array[0]; for (int i=1; i < size; i++) { if (isBefore(array[maxIndex],array[i])) { maxIndex = i; //maxValue = array[i]; } } return maxIndex; } // What does this function do? //sorting the array //selection sort void selectionSort(double* *arrayIn, int sizeIn) { for(int size = sizeIn; size > 1; size--) { //int k = maxIndex(arrayIn,size); swap(arrayIn[maxIndex(arrayIn,size)], arrayIn[size-1]); //int temp = arrayIn[size-1]; //arrayIn[size-1] = arrayIn[k]; //arrayIn[k] = temp; } } void swap(double*& a, double*& b) { double* temp = a; a = b; b = temp; } bool isBefore(double* a, double* b) { return magnitude(a) < magnitude(b); } // Read in a point (x,y,z) coordinates -- return as array double* readPoint(istream &in) { double *point = new double[3]; in >> point[0]; in >> point[1]; in >> point[2]; return point; } // Write the point to cout void writePoint(double *point, ostream &out) { out << point[0] << "," << point[1] << "," << point[2]; } // Calculates magnitude of given array of 3 doubles (x,y,z) double magnitude(double *point) { double sum = point[0]*point[0] + point[1]*point[1] + point[2]*point[2]; return sqrt(sum); }