fork download
  1. #include <stdlib.h>
  2.  
  3. typedef struct Element
  4. {
  5. int data;
  6. struct Element* next;
  7. } Element;
  8.  
  9. typedef Element* List;
  10.  
  11.  
  12. int compare_elements_greater(const Element *lhs, const Element *rhs)
  13. {
  14. return lhs->data > rhs->data;
  15. }
  16.  
  17.  
  18. void bubble_sort(List *root, int (*comparison)(const Element*, const Element*))
  19. {
  20. // If the list has 0 or 1 element, it is already sorted:
  21. if (! *root || !(*root)->next)
  22. return;
  23.  
  24. // Otherwise use extra stupid sort:
  25. int num_changes;
  26. do
  27. {
  28. num_changes = 0;
  29. Element **p1 = root;
  30. Element *p2 = *root;
  31. Element *p3 = (*root)->next;
  32.  
  33. while (p3)
  34. {
  35. if (comparison(p2, p3))
  36. {
  37. ++num_changes;
  38.  
  39. *p1 = p3;
  40. p2->next = p3->next;
  41. p3->next = p2;
  42.  
  43. p1 = &p3->next;
  44. p3 = p2->next;
  45. }
  46. else
  47. {
  48. p1 = &p2->next;
  49. p2 = p3;
  50. p3 = p3->next;
  51. }
  52. }
  53. }
  54. while (num_changes);
  55. }
  56.  
  57.  
  58. List create_list()
  59. {
  60. return NULL;
  61. }
  62.  
  63.  
  64. int insert_list(int value, List *list)
  65. {
  66. List old_list = *list;
  67. *list = malloc(sizeof(Element));
  68. if (*list)
  69. {
  70. (*list)->data = value;
  71. (*list)->next = old_list;
  72. return 1;
  73. }
  74. else
  75. {
  76. *list = old_list;
  77. return 0;
  78. }
  79. }
  80.  
  81.  
  82. void delete_list(List* list)
  83. {
  84. while (*list)
  85. {
  86. List next = (*list)->next;
  87. free(*list);
  88. *list = next;
  89. }
  90. }
  91.  
  92.  
  93. List iterate_list(List *list)
  94. {
  95. *list = (*list)->next;
  96. return *list;
  97. }
  98.  
  99.  
  100. int get_list_data(List list)
  101. {
  102. return list->data;
  103. }
  104.  
  105.  
  106.  
  107. #include <time.h>
  108. #include <stdio.h>
  109.  
  110. int main()
  111. {
  112. List list = create_list();
  113.  
  114. srand(time(0));
  115. for(int i = 0; i < 25; ++i)
  116. {
  117. if (!insert_list(rand() % 42, &list))
  118. {
  119. fputs("Fehler beim Einfügen!\n", stderr);
  120. goto Exception;
  121. }
  122. }
  123.  
  124. bubble_sort(&list, &compare_elements_greater);
  125.  
  126. for(List iterator = list; iterator; iterate_list(&iterator))
  127. {
  128. printf("%d\n", get_list_data(iterator));
  129. }
  130.  
  131. Exception:
  132. delete_list(&list);
  133. }
  134.  
Success #stdin #stdout 0s 1964KB
stdin
Standard input is empty
stdout
1
1
2
2
6
10
11
11
11
13
17
19
21
24
24
24
24
26
27
30
31
36
37
38
40