Sorting coordinates

My algorithm is unable to successfully sort input in ascending order of the magnitude of hypotenuse from the origin. Please advice on my code written below, thanks.

void sort(point_t arr[], int size) {
int i, j, m, hypo, alt_hypo;
point_t temp;

for(i=0;i<size;i++) {
hypo = (arr[i].x * arr[i].x) + (arr[i].y * arr[i].y);
for(j=i+1,m=i;j<size;j++) {
alt_hypo = (arr[j].x * arr[j].x) + (arr[j].y + arr[j].y);
if(alt_hypo < hypo)
m = j;
}
temp = arr[i];
arr[i] = arr[m];
arr[m] = temp;
}
}
Just add an operator< function to your point structure and compare the sum of squares:

1
2
3
4
5
6
7
8
9
struct point_t
{
  double x;
  double y;

  bool operator<(point_t& rhs) { return (x*x+y*y) < (rhs.x*rhs.x + rhs.y*rhs.y); }
} *arr;

std::sort(arr, arr+size);
Last edited on
Topic archived. No new replies allowed.