fork(2) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // point type
  5.  
  6. typedef struct {
  7. int x;
  8. int y;
  9. } Point;
  10.  
  11. // point compare function
  12.  
  13. int compare_points(const void *p1, const void *p2)
  14. {
  15. const Point *pt1 = p1;
  16. const Point *pt2 = p2;
  17.  
  18. // do primary compare on x
  19. if (pt1->x > pt2->x)
  20. return 1;
  21. if (pt1->x < pt2->x)
  22. return -1;
  23.  
  24. // pt1->x == pt2->x - do secondary compare on y...
  25. if (pt1->y > pt2->y)
  26. return 1;
  27. if (pt1->y < pt2->y)
  28. return -1;
  29.  
  30. // pt1 == pt2
  31. return 0;
  32. }
  33.  
  34. int main()
  35. {
  36. #define num_points 4
  37. Point points[num_points] = { { 2, 3 }, { 4, 2 }, { 4, -1 }, { -1, 3 } };
  38. int i;
  39.  
  40. printf("BEFORE:\n");
  41. for (i = 0; i < num_points; ++i)
  42. printf("{ %d, %d }\n", points[i].x, points[i].y);
  43.  
  44. // sort array of points...
  45. qsort(points, num_points, sizeof(Point), compare_points);
  46.  
  47. printf("AFTER:\n");
  48. for (i = 0; i < num_points; ++i)
  49. printf("{ %d, %d }\n", points[i].x, points[i].y);
  50.  
  51. return 0;
  52. }
  53.  
  54.  
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
BEFORE:
{ 2, 3 }
{ 4, 2 }
{ 4, -1 }
{ -1, 3 }
AFTER:
{ -1, 3 }
{ 2, 3 }
{ 4, -1 }
{ 4, 2 }