Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- typedef struct type {
- int size;
- int (*cmp)(void*, void*);
- } type_t;
- void tri_bulle(type_t element_type, void *elements, unsigned int nb_elements)
- {
- unsigned int i;
- unsigned char changed=0;
- void *buffer = malloc( element_type.size );
- int result;
- do
- {
- changed = 0;
- for(i=0; i<nb_elements; i++)
- {
- if( element_type.cmp(
- ((char*)elements+(i+1)*element_type.size),
- ((char*)elements+(i)*element_type.size)
- )
- )
- {
- memcpy(buffer, ((char *)elements+(i+1)*element_type.size), element_type.size);
- memcpy(((char *)elements+(i+1)*element_type.size), ((char *)elements+i*element_type.size), element_type.size);//elements[i+1] = elements[i];
- memcpy(((char *)elements+i*element_type.size), buffer, element_type.size);//elements[i] = *buffer;
- changed=1;
- }
- }
- }while(changed);
- }
- int cmp_double(void *a, void *b)
- {
- return ( *(double*)a < *(double*)b );
- }
- int cmp_char(void *a, void *b)
- {
- return ( *(char*)a < *(char*)b );
- }
- int cmp_short(void *a, void *b)
- {
- return ( *(short*)a < *(short*)b );
- }
- int main(int argc, char *argv[])
- {
- unsigned char i;
- type_t struct_char;
- type_t struct_double;
- type_t struct_short;
- struct_char.size = sizeof(char);
- struct_char.cmp = cmp_char;
- struct_short.size = sizeof(short);
- struct_short.cmp = cmp_short;
- struct_double.size = sizeof(double);
- struct_double.cmp = cmp_double;
- char table_char[10] = {1, 10, 45, 4, 6, 32, 34, 56, 7, 11};
- short table_short[10] = {1, 10, 45, 4, 6, 32, 34, 56, 7, 11};
- double table_double[10] = {100, 25, -1, 17, -50, 46, 57331, 8, -100, 12};
- tri_bulle(struct_char, table_char, 10);
- tri_bulle(struct_short, table_short, 10);
- tri_bulle(struct_double, table_double, 10);
- for(i=0; i<10; i++)
- printf("%d ", (int)table_char[i]);
- printf("\n");
- for(i=0; i<10; i++)
- printf("%d ", (int)table_short[i]);
- printf("\n");
- for(i=0; i<10; i++)
- printf("%f ", table_double[i]);
- return 0;
- }
Add Comment
Please, Sign In to add comment