Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following typedef for a point in the cartesian plane: typedef struc

ID: 3598257 • Letter: C

Question

Consider the following typedef for a point in the cartesian plane:

typedef struct {

double x;

double y;

} POINT;

Now, do you remember the qsort library function from your Week-3 Lab? (If not you know where to find it.)

Your task: write a comparator function which can be passed to qsort to sort an array of points according to these rules:

The points are increasing order of their x-coordinates.

If two points have the same x-coordinate, their y-coordinate is used as a tie-breaker (the point with the smaller y-coordinate comes first)

If two points are identical in both coordinates, then of course they are considered equal.

You will not submit any C files through blackboard. Just include your solution in the writeup of this homework. You definitely should program it and test it though -- we just don't need electronic submission of your source files.

What to include:

The code for your comparator function.

Completion of the main function below to include a correct invocation of qsort using your comparator function on the array points[].

typedef struct {

double x;

double y;

} POINT;

int main(){

POINT points[] = {{2.9, 1.1}, {0.8, 2.3}, {2.9, 0.6}, {1.1, 3.14}, {0.8, 4.6}};

   // your call to qsort here!

return 0;

}

typedef struct {

double x;

double y;

} POINT;

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>

typedef struct{
double x;
double y;
}POINT;

int comparator(const void *ptr1, const void *ptr2){
const POINT *point1 = (const POINT *)ptr1;
const POINT *point2 = (const POINT *)ptr2;
if(point1->x != point2->x) // If x has different values
return (point1->x - point2->x); // return the difference
else{ // otherwise compare the y values
return (point1->y - point2->y); // return the difference of y values
}
}

int main(){
int i;
POINT points[] = {{2.9, 1.1}, {0.8, 2.3}, {2.9, 0.6}, {1.1, 3.14}, {0.8, 4.6}};
qsort((void*)points, 5, sizeof(POINT), comparator);
return 0;
}