Guest User

sort.c

a guest
Sep 21st, 2023
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node {
  5.     int i;
  6.     struct node *next;
  7. } List;
  8.  
  9. List *cons(int i, List *l) {
  10.     List *n = malloc(sizeof(List));
  11.     n->i = i;
  12.     n->next = l;
  13.     return n;
  14. }
  15.  
  16. void printl(List *l) {
  17.     if (l == NULL) {
  18.         printf("\n");
  19.         return;
  20.     }
  21.     printf("%d ", l->i);
  22.     printl(l->next);
  23. }
  24.  
  25. List *biggerthan(List *l, int x) {
  26.     if (l == NULL) {
  27.         return NULL;
  28.     }
  29.     if (l->i > x) {
  30.         return cons(l->i, biggerthan(l->next, x));
  31.     }
  32.     return biggerthan(l->next, x);
  33. }
  34.  
  35. List *smallerthan(List *l, int x) {
  36.     if (l == NULL) {
  37.         return NULL;
  38.     }
  39.     if (l->i < x) {
  40.         return cons(l->i, smallerthan(l->next, x));
  41.     }
  42.     return smallerthan(l->next, x);
  43. }
  44.  
  45. List *eqto(List *l, int x) {
  46.     if (l == NULL) {
  47.         return NULL;
  48.     }
  49.     if (l->i == x) {
  50.         return cons(l->i, eqto(l->next, x));
  51.     }
  52.     return eqto(l->next, x);
  53. }
  54.  
  55. List *merge(List *l1, List *l2) {
  56.     if (l1 == NULL) {
  57.         return l2;
  58.     }
  59.     if (l2 == NULL) {
  60.         return l1;
  61.     }
  62.     if (l1->i < l2->i) {
  63.         return cons(l1->i, merge(l1->next, l2));
  64.     }
  65.     return cons(l2->i, merge(l1, l2->next));
  66. }
  67.  
  68. List *append(List *l1, List *l2) {
  69.     if (l1 == NULL) {
  70.         if (l2 == NULL) {
  71.             return NULL;
  72.         }
  73.         return append(l2, NULL);;
  74.     }
  75.     return cons(l1->i, append(l1->next, l2));
  76. }
  77.  
  78. List *sort(List *l) {
  79.     if (l == NULL) {
  80.         return l;
  81.     }
  82.     return merge(
  83.             sort(smallerthan(l, l->i)),
  84.             append(eqto(l, l->i), sort(biggerthan(l, l->i)))
  85.             );
  86. }
  87.  
  88. int main() {
  89.     List *l = NULL;
  90.     l = cons(3, l);
  91.     l = cons(1, l);
  92.     l = cons(4, l);
  93.     l = cons(1, l);
  94.     l = cons(5, l);
  95.     l = cons(9, l);
  96.     l = cons(2, l);
  97.     l = cons(6, l);
  98.     l = cons(5, l);
  99.     l = cons(3, l);
  100.    
  101.     printl(l);
  102.     printf("Sorted: \n");
  103.     List *sorted = sort(l);
  104.     printl(sorted);
  105. }
  106.  
Advertisement
Add Comment
Please, Sign In to add comment