Write a program that reads 10 pairs of
Cartesian coordinates from a file called "points.txt" and
sorts them by increasing x-values, decreasing y-values,
and increasing distance from the origin. Use only one
sorting routine. Use an enumerated data type to keep
track of the field on which the list is being sorted. The
number of pairs should be in a global constant.
1
Expert's answer
2016-05-05T08:28:02-0400
#include <fstream> #include <iostream>
using namespace std; const int NUMBER_OF_PAIRS = 10;
struct Point{ int x; int y;
Point() {} Point(int c_x, int c_y) { x = c_x; y = c_y; } };
void sort(Point* array);
int main() { fstream file("points.txt"); Point points[NUMBER_OF_PAIRS]; for (int i = 0; i < NUMBER_OF_PAIRS; i++){ int x; int y; file >> x; file >> y; points[i] = Point(x, y); } sort(points); return 0; }
void sort(Point* array) { for (int i = 0; i < NUMBER_OF_PAIRS - 1; i++) { for (int j = i + 1; j < NUMBER_OF_PAIRS; j++) { if (array[i].x > array[j].x) { Point extra = array[i]; array[i] = array[j]; array[j] = extra; } } } for (int i = 0; i < NUMBER_OF_PAIRS - 1; i++) { for (int j = i + 1; j < NUMBER_OF_PAIRS; j++) { if (array[i].x == array[j].x && array[i].y < array[j].y) { Point extra = array[i]; array[i] = array[j]; array[j] = extra; } } } }
Comments
Leave a comment