2 /* Block Sorting Optimizado en memoria! */
8 typedef struct _bs_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 char es_menor(char *data, t_BlockSort *array, int n, int i, int j)
17 unsigned long int pi, pj, k;
20 pi = (array[i].pos_inicial+k)%n;
21 pj = (array[j].pos_inicial+k)%n;
23 if (data[pi] > data[pj]) return 0;
24 if (data[pi] < data[pj]) return 1;
30 void generar_array(char *data, t_BlockSort *array, unsigned long int n)
34 array[i].pos_inicial = i;
35 array[i].pos_final = (i+n-1)%n;
36 array[i].pos_orden = 0;
41 void ordenar_array(char *data, t_BlockSort *array, t_BlockSort *ord, unsigned long int n)
43 unsigned long int i, j, min;
48 if (array[j].ord) continue;
49 if ((min==-1) || (es_menor(data, array, n, j, min)))
54 array[min].pos_orden = i;
60 int generar_salida(char *data, t_BlockSort *array, char *salida, int n)
62 unsigned long int i, k;
65 salida[i] = data[array[i].pos_final];
66 if (array[i].pos_inicial == 0) k = i;
71 void block_sorting(char *in, char *out, unsigned long int *k, unsigned long int len)
73 static t_BlockSort *array = NULL;
74 static t_BlockSort *ord = NULL;
76 if (!array) array = malloc(sizeof(t_BlockSort)*len);
77 if (!ord) ord = malloc(sizeof(t_BlockSort)*len);
79 generar_array(in, array, len);
80 ordenar_array(in, array, ord, len);
81 (*k) = generar_salida(in, ord, out, len);
84 int main(int argc, char *argv[])
88 unsigned long int len, i, k;
93 printf("Modo de uso : %s <archivo datos> <tamaño pagina>\n", argv[0]);
97 fp = fopen(argv[1], "r");
100 data = malloc(sizeof(char)*len);
101 salida = malloc(sizeof(char)*len);
103 while ((c = fgetc(fp)) != EOF) {
104 memset(salida, 0, len*sizeof(char));
106 while ((c!=EOF) && (i < len)) {
110 block_sorting(data, salida, &k, (i<len)?i:len);
111 printf("Salida = (%s) con k=%ld\n", salida, k);