Guest User

Untitled

a guest
Oct 20th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. typedef struct type {
  5. int size;
  6. int (*cmp)(void*, void*);
  7. } type_t;
  8.  
  9. void tri_bulle(type_t element_type, void *elements, unsigned int nb_elements)
  10. {
  11. unsigned int i;
  12. unsigned char changed=0;
  13. void *buffer = malloc( element_type.size );
  14. int result;
  15.  
  16. do
  17. {
  18. changed = 0;
  19. for(i=0; i<nb_elements; i++)
  20. {
  21. if( element_type.cmp(
  22. ((char*)elements+(i+1)*element_type.size),
  23. ((char*)elements+(i)*element_type.size)
  24. )
  25. )
  26. {
  27. memcpy(buffer, ((char *)elements+(i+1)*element_type.size), element_type.size);
  28. memcpy(((char *)elements+(i+1)*element_type.size), ((char *)elements+i*element_type.size), element_type.size);//elements[i+1] = elements[i];
  29. memcpy(((char *)elements+i*element_type.size), buffer, element_type.size);//elements[i] = *buffer;
  30. changed=1;
  31. }
  32. }
  33. }while(changed);
  34. }
  35.  
  36. int cmp_double(void *a, void *b)
  37. {
  38. return ( *(double*)a < *(double*)b );
  39. }
  40.  
  41. int cmp_char(void *a, void *b)
  42. {
  43. return ( *(char*)a < *(char*)b );
  44. }
  45.  
  46. int cmp_short(void *a, void *b)
  47. {
  48. return ( *(short*)a < *(short*)b );
  49. }
  50.  
  51. int main(int argc, char *argv[])
  52. {
  53. unsigned char i;
  54. type_t struct_char;
  55. type_t struct_double;
  56. type_t struct_short;
  57.  
  58. struct_char.size = sizeof(char);
  59. struct_char.cmp = cmp_char;
  60. struct_short.size = sizeof(short);
  61. struct_short.cmp = cmp_short;
  62. struct_double.size = sizeof(double);
  63. struct_double.cmp = cmp_double;
  64.  
  65. char table_char[10] = {1, 10, 45, 4, 6, 32, 34, 56, 7, 11};
  66. short table_short[10] = {1, 10, 45, 4, 6, 32, 34, 56, 7, 11};
  67. double table_double[10] = {100, 25, -1, 17, -50, 46, 57331, 8, -100, 12};
  68.  
  69. tri_bulle(struct_char, table_char, 10);
  70. tri_bulle(struct_short, table_short, 10);
  71. tri_bulle(struct_double, table_double, 10);
  72.  
  73. for(i=0; i<10; i++)
  74. printf("%d ", (int)table_char[i]);
  75.  
  76. printf("\n");
  77.  
  78. for(i=0; i<10; i++)
  79. printf("%d ", (int)table_short[i]);
  80.  
  81. printf("\n");
  82.  
  83. for(i=0; i<10; i++)
  84. printf("%f ", table_double[i]);
  85.  
  86. return 0;
  87. }
Add Comment
Please, Sign In to add comment