2 /* Block Sorting Optimizado en memoria! */
8 typedef struct _bs_data_t_ {
9 unsigned long int pos_inicial;
10 unsigned long int pos_final;
11 unsigned long int pos_orden;
12 char ord; /* indice si esta ordenada */
15 typedef struct _bs_t_ {
16 t_BlockSortData *array;
17 unsigned long int *ord;
18 unsigned long int len;
21 typedef struct _bs_decode_t_ {
23 unsigned long int pos;
26 int _compare(const void *d1, const void *d2) {
27 t_BlockSortDecode *s1, *s2;
29 s1 = (t_BlockSortDecode *)d1;
30 s2 = (t_BlockSortDecode *)d2;
32 return (s1->c - s2->c);
35 char es_menor(char *data, t_BlockSort *bs, int i, int j)
37 unsigned long int pi, pj, k;
39 for(k=0; k<bs->len; k++) {
40 pi = (bs->array[i].pos_inicial+k)%bs->len;
41 pj = (bs->array[j].pos_inicial+k)%bs->len;
43 if (data[pi] > data[pj]) return 0;
44 if (data[pi] < data[pj]) return 1;
50 void generar_array(char *data, t_BlockSort *bs)
53 for(i=0; i<bs->len; i++) {
54 bs->array[i].pos_inicial = i;
55 bs->array[i].pos_final = (i+bs->len-1)%bs->len;
56 bs->array[i].pos_orden = 0;
61 void ordenar_array(char *data, t_BlockSort *bs)
63 unsigned long int i, j, min;
65 for(i=0; i<bs->len; i++) {
67 for(j=0; j<bs->len; j++) {
68 if (bs->array[j].ord) continue;
69 if ((min==-1) || (es_menor(data, bs, j, min)))
73 bs->array[min].ord = 1;
74 bs->array[min].pos_orden = i;
80 int generar_salida(char *data, t_BlockSort *bs, char *salida)
82 unsigned long int i, k;
84 for(i=0; i<bs->len; i++) {
85 salida[i] = data[bs->array[bs->ord[i]].pos_final];
86 if (bs->array[bs->ord[i]].pos_inicial == 0) k = i;
91 void bs_solve(char *in, char *out, t_BlockSort *bs, unsigned long int *k, unsigned int leido)
95 /* Hack para pedasos menores a la pagina */
96 if (leido < bs->len) bs->len = leido;
98 generar_array(in, bs);
99 ordenar_array(in, bs);
100 (*k) = generar_salida(in, bs, out);
105 void bs_restore(char *dst, char *c, unsigned long int k, unsigned long int len)
107 unsigned long int i, current;
108 t_BlockSortDecode *in;
110 in = malloc(sizeof(t_BlockSortDecode)*len);
112 for(i=0; i<len; i++) {
117 qsort(in, len, sizeof(t_BlockSortDecode), _compare);
122 dst[i++] = in[current].c;
123 current = in[current].pos;
124 } while (current != k);
128 t_BlockSort *bs_create(unsigned int len)
132 tmp = malloc(sizeof(t_BlockSort));
133 tmp->array = malloc(sizeof(t_BlockSortData)*len);
134 tmp->ord = malloc(sizeof(unsigned long int)*len);
141 void bs_destroy(t_BlockSort *bs)
148 int main(int argc, char *argv[])
152 unsigned long int len, i, k;
158 printf("Modo de uso : %s <archivo datos> <tamaƱo pagina>\n", argv[0]);
162 fp = fopen(argv[1], "r");
165 data = malloc(sizeof(char)*len);
166 salida = malloc(sizeof(char)*(len+1));
171 while ((c = fgetc(fp)) != EOF) {
173 while ((c!=EOF) && (i < len)) {
177 bs_solve(data, salida, bs, &k, i);
179 /* XXX ACA SALIDA DEBERIA PASAR A LA SIGUIENTE ETAPA XXX */
180 printf("%s -> %ld\n", salida, k);