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 /* Hack si es el mismo caracter, dejo como mejor la de menor sig */
22 return (s1->sig - s2->sig);
25 return (s1->c - s2->c);
28 int __compare(const void *d1, const void *d2) {
29 t_BlockSortData *s1, *s2;
31 s1 = (t_BlockSortData *)d1;
32 s2 = (t_BlockSortData *)d2;
34 return es_menor(s1->bs->data, s1->bs, s1->pos_inicial, s2->pos_inicial);
37 char es_menor(char *data, t_BlockSort *bs, int i, int j)
41 for(k=0; k<bs->len; k++) {
45 if (data[pi] > data[pj]) return 1; /* El primero es mayor */
46 if (data[pi] < data[pj]) return -1; /* El primero es menor */
53 void generar_array(char *data, t_BlockSort *bs)
56 for(i=0; i<bs->len; i++) {
57 bs->array[i].pos_inicial = i;
58 bs->array[i].pos_final = (i+bs->len-1)%bs->len;
59 bs->array[i].ord = (i==0)?1:0;
64 void ordenar_array(char *data, t_BlockSort *bs)
66 qsort(bs->array, bs->len, sizeof(t_BlockSortData), __compare);
69 int generar_salida(char *data, t_BlockSort *bs, char *salida)
74 /* Dejo lugar para guardar el K */
75 out = salida + sizeof(Uint32);
78 for(i=0; i<bs->len; i++) {
79 out[i] = data[bs->array[i].pos_final];
80 if (bs->array[i].ord == 1) k = i;
85 void bs_solve(char *in, char *out, t_BlockSort *bs, Uint32 *k, Uint32 leido)
89 /* Hack para pedasos menores a la pagina */
90 if (leido < bs->len) bs->len = leido;
93 generar_array(in, bs);
94 ordenar_array(in, bs);
95 (*k) = generar_salida(in, bs, out);
97 /* Guardo el k y el tamaƱo en el array */
98 memcpy(out, k, sizeof(Uint32));
102 void bs_restore(char *dst, char *c, Uint32 k, Uint32 len)
105 t_BlockSortDecode *in;
107 in = malloc(sizeof(t_BlockSortDecode)*len);
109 for(i=0; i<len; i++) {
114 qsort(in, len, sizeof(t_BlockSortDecode), _compare);
119 dst[i++] = in[current].c;
120 current = in[current].sig;
121 } while (current != k);
125 t_BlockSort *bs_create(Uint32 len)
129 tmp = malloc(sizeof(t_BlockSort));
130 tmp->array = malloc(sizeof(t_BlockSortData)*len);
137 void bs_destroy(t_BlockSort *bs)
143 int bs_readblock(FILE *fp, char *data, Uint32 pagesize)
147 while ((!feof(fp)) && (i < pagesize)) {
148 data[i++] = fgetc(fp);
151 /* Saco un EOF que lee de mas */