Answer to Question #59746 in C++ for adrain

Question #59746
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;
}
}
}
}



// points.txt

3 4
5 6
2 4
3 8
4 1
5 1
4 3
2 7
2 9
5 7

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS