4 /* Block Sorting Optimizado en memoria! */
6 typedef struct _bs_decode_t_ {
11 int _compare(const void *d1, const void *d2) {
12 t_BlockSortDecode *s1, *s2;
14 s1 = (t_BlockSortDecode *)d1;
15 s2 = (t_BlockSortDecode *)d2;
17 return (s1->c - s2->c);
20 char es_menor(char *data, t_BlockSort *bs, int i, int j)
22 unsigned long int pi, pj, k;
24 for(k=0; k<bs->len; k++) {
25 pi = (bs->array[i].pos_inicial+k)%bs->len;
26 pj = (bs->array[j].pos_inicial+k)%bs->len;
28 if (data[pi] > data[pj]) return 0;
29 if (data[pi] < data[pj]) return 1;
35 void generar_array(char *data, t_BlockSort *bs)
38 for(i=0; i<bs->len; i++) {
39 bs->array[i].pos_inicial = i;
40 bs->array[i].pos_final = (i+bs->len-1)%bs->len;
41 bs->array[i].pos_orden = 0;
46 void ordenar_array(char *data, t_BlockSort *bs)
48 unsigned long int i, j, min;
50 for(i=0; i<bs->len; i++) {
52 for(j=0; j<bs->len; j++) {
53 if (bs->array[j].ord) continue;
54 if ((min==-1) || (es_menor(data, bs, j, min)))
58 bs->array[min].ord = 1;
59 bs->array[min].pos_orden = i;
65 int generar_salida(char *data, t_BlockSort *bs, char *salida)
67 unsigned long int i, k;
69 for(i=0; i<bs->len; i++) {
70 salida[i] = data[bs->array[bs->ord[i]].pos_final];
71 if (bs->array[bs->ord[i]].pos_inicial == 0) k = i;
76 void bs_solve(char *in, char *out, t_BlockSort *bs, unsigned long int *k, unsigned int leido)
80 /* Hack para pedasos menores a la pagina */
81 if (leido < bs->len) bs->len = leido;
83 generar_array(in, bs);
84 ordenar_array(in, bs);
85 (*k) = generar_salida(in, bs, out);
90 void bs_restore(char *dst, char *c, unsigned long int k, unsigned long int len)
92 unsigned long int i, current;
93 t_BlockSortDecode *in;
95 in = malloc(sizeof(t_BlockSortDecode)*len);
97 for(i=0; i<len; i++) {
102 qsort(in, len, sizeof(t_BlockSortDecode), _compare);
107 dst[i++] = in[current].c;
108 current = in[current].pos;
109 } while (current != k);
113 t_BlockSort *bs_create(unsigned long int len)
117 tmp = malloc(sizeof(t_BlockSort));
118 tmp->array = malloc(sizeof(t_BlockSortData)*len);
119 tmp->ord = malloc(sizeof(unsigned long int)*len);
126 void bs_destroy(t_BlockSort *bs)