5 /* Block Sorting Optimizado en memoria! */
7 typedef struct _bs_decode_t_ {
12 char es_menor(char *data, t_BlockSort *bs, int i, int j);
14 int _compare(const void *d1, const void *d2) {
15 t_BlockSortDecode *s1, *s2;
17 s1 = (t_BlockSortDecode *)d1;
18 s2 = (t_BlockSortDecode *)d2;
20 return (s1->c - s2->c);
23 int __compare(const void *d1, const void *d2) {
24 t_BlockSortData *s1, *s2;
26 s1 = (t_BlockSortData *)d1;
27 s2 = (t_BlockSortData *)d2;
29 return es_menor(s1->bs->data, s1->bs, s1->pos_inicial, s2->pos_inicial);
32 char es_menor(char *data, t_BlockSort *bs, int i, int j)
34 unsigned long int pi, pj, k;
36 for(k=0; k<bs->len; k++) {
40 if (data[pi] > data[pj]) return 1; /* El primero es mayor */
41 if (data[pi] < data[pj]) return -1; /* El primero es menor */
48 void generar_array(char *data, t_BlockSort *bs)
51 for(i=0; i<bs->len; i++) {
52 bs->array[i].pos_inicial = i;
53 bs->array[i].pos_final = (i+bs->len-1)%bs->len;
54 bs->array[i].ord = (i==0)?1:0;
59 void ordenar_array(char *data, t_BlockSort *bs)
61 qsort(bs->array, bs->len, sizeof(t_BlockSortData), __compare);
64 void print_(char *data, unsigned long int pos, unsigned long int len)
69 printf("%c", data[(pos+i)%len]);
73 int generar_salida(char *data, t_BlockSort *bs, char *salida)
75 unsigned long int i, k;
78 /* Dejo lugar para guardar el k y el tamaño de este bloque */
79 out = salida + sizeof(unsigned long int)*2;
82 for(i=0; i<bs->len; i++) {
83 /* print_(data, bs->array[i].pos_inicial, bs->len); */
84 out[i] = data[bs->array[i].pos_final];
85 if (bs->array[i].ord == 1) k = i;
90 void bs_solve(char *in, char *out, t_BlockSort *bs, unsigned long int *k, unsigned int leido)
94 /* Hack para pedasos menores a la pagina */
95 if (leido < bs->len) bs->len = leido;
98 generar_array(in, bs);
99 ordenar_array(in, bs);
100 (*k) = generar_salida(in, bs, out);
102 /* Guardo el k y el tamaño en el array */
103 memcpy(out, &leido, sizeof(unsigned long int));
104 memcpy(out+sizeof(unsigned long int), k, sizeof(unsigned long int));
109 void bs_restore(char *dst, char *c, unsigned long int k, unsigned long int len)
111 unsigned long int i, current;
112 t_BlockSortDecode *in;
114 in = malloc(sizeof(t_BlockSortDecode)*len);
116 for(i=0; i<len; i++) {
121 qsort(in, len, sizeof(t_BlockSortDecode), _compare);
126 dst[i++] = in[current].c;
127 current = in[current].pos;
128 } while (current != k);
132 t_BlockSort *bs_create(unsigned long int len)
136 tmp = malloc(sizeof(t_BlockSort));
137 tmp->array = malloc(sizeof(t_BlockSortData)*len);
144 void bs_destroy(t_BlockSort *bs)