fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. typedef int (*comparator_t)(void*, void*);
  5.  
  6. void bubble_sort(void *items, size_t size, size_t count, comparator_t compare) {
  7. int i, j;
  8. char temp[size];
  9. for(i = 0; i < count - 1; ++i) {
  10. for(j = i + 1; j < count; ++j) {
  11. if (compare(items + (i * size), items + (j * size)) == 1) {
  12. memcpy(temp, items + (i * size), size);
  13. memcpy(items + i * size, items + (j * size), size);
  14. memcpy(items + (j * size), temp, size);
  15. }
  16. }
  17. }
  18. }
  19.  
  20. int compare_long(void* p_a, void* p_b) {
  21. long a = *(long*)p_a;
  22. long b = *(long*)p_b;
  23.  
  24. if(a < b) return -1;
  25. if(a > b) return 1;
  26. return 0;
  27. }
  28.  
  29. int main(int argc, char *argv[]) {
  30. long x[] = { 5, 6, 1, 2, 9 };
  31. int i;
  32.  
  33. for (i = 0; i < 5; ++i) printf("%ld ", x[i]);
  34. printf("\n");
  35.  
  36. bubble_sort(x, sizeof(long), 5, compare_long);
  37.  
  38. for (i = 0; i < 5; ++i) printf("%ld ", x[i]);
  39. }
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
5 6 1 2 9 
1 2 5 6 9