Advertisement
cd62131

Sort Struct

Jan 21st, 2014
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct {
  4.   double a;
  5.   double b;
  6.   double div;
  7. } data_t;
  8. int data_compare(const void *p1, const void *p2) {
  9.   data_t *q1 = (data_t *) p1;
  10.   data_t *q2 = (data_t *) p2;
  11.   if (q1->div < q2->div) return 1;
  12.   else if (q1->div > q2->div) return -1;
  13.   else if (q1->a < q2->a) return -1;
  14.   else if (q1->a > q2->a) return 1;
  15.   else if (q1->b < q2->b) return -1;
  16.   else if (q1->b > q2->b) return 1;
  17.   return 0;
  18. }
  19. int main(void) {
  20.   double a[] = { 2., 8., 4., 5., 10. };
  21.   double b[] = { 3., 5., 4., 7., 10. };
  22.   int n = sizeof(a) / sizeof(double);
  23.   data_t dat[n];
  24.   for (int i = 0; i < n; i++) {
  25.     dat[i].a = a[i];
  26.     dat[i].b = b[i];
  27.     dat[i].div = a[i] / b[i];
  28.   }
  29.   for (int i = 0; i < n; i++) {
  30.     printf("%2d %3.1lf %3.1lf %5.2lf\n", i + 1, dat[i].a, dat[i].b, dat[i].div);
  31.   }
  32.   puts("");
  33.   qsort(dat, n, sizeof(data_t), data_compare);
  34.   for (int i = 0; i < n; i++) {
  35.     printf("%2d %3.1lf %3.1lf %5.2lf\n", i + 1, dat[i].a, dat[i].b, dat[i].div);
  36.   }
  37.   return EXIT_SUCCESS;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement