Advertisement
anechka_ne_plach

Untitled

Feb 8th, 2022
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include <inttypes.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5.  
  6. typedef struct data {
  7.     int (*get_rank)(const struct data*);
  8.     int rank;
  9. } data;
  10.  
  11. int get_rank(const data* d) {
  12.     return (d->rank);
  13. }
  14.  
  15. int strcmp(const void * x1, const void * x2)
  16. {
  17.     data* t1 = (data*)x1;
  18.     data* t2 = (data*)x2;
  19.     return (t1->get_rank(t1) - t2->get_rank(t2));              
  20. }
  21.  
  22. typedef int (*comparator_t)(const void *, const void *);
  23.  
  24. comparator_t comp = strcmp;
  25.  
  26. void rank_sort(data* elements[], size_t size) {
  27.     qsort(elements, size, sizeof(data*), comp);
  28. }
  29.  
  30. enum {
  31.     syze = 3
  32. };
  33.  
  34. int main() {
  35.     data* a = malloc(sizeof(data));
  36.     a->rank = 1;
  37.     data* b = malloc(sizeof(data));
  38.     b->rank = 2;
  39.     data* c = malloc(sizeof(data));
  40.     c->rank = 3;
  41.     data* els[] = {c, a, b};
  42.     for (int i = 0; i < syze; +i) {
  43.         printf("%d ", els[i]->get_rank(els[i]));
  44.     }
  45.     printf("\n");
  46.  
  47.     rank_sort(els, syze);
  48.  
  49.     for (int i = 0; i < syze; +i) {
  50.         printf("%d ", els[i]->get_rank(els[i]));
  51.     }
  52.     printf("\n");
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement