/******************************************************************************* * K&R 5-7 * * Line sorting program using pointers * * program: linesort * * Using a local char array instead of alloc() * * date: 14 November 2024 * * ~yetimach ******************************************************************************/ #include #include #define LOCALBUFSIZE 50000 #define MAXLEN 1000 #define MAXLINES 50 char *lineptr[MAXLINES]; void my_swap(char *v[], int i, int j){ char *temp; temp = v[i]; v[i] = v[j]; v[j] = temp; } void my_qsort(char *v[], int left, int right){ int i, last; if (left >= right) return; my_swap(v, left, (left + right)/2); last = left; for (i = left+1; i <= right; i++) if (strcmp(v[i], v[left]) < 0) my_swap(v, ++last, i); my_swap(v, left, last); my_qsort(v, left, last-1); my_qsort(v, last+1, right); } void writelines(char *lptr[], int nlines){ while (nlines-- > 0) printf("%s\n", *lptr++); } int my_getline(char *s, int max){ int c, i; for (i = 0; i < max-1 && (c = getchar()) != '\n' && c != EOF; *s++ = c, i++) ; *s = '\0'; if (i >= max-1) return -1; else return i; } int readlines(char *lptr[], char lb[], int maxlines){ int len, nlines, i; static int lbl = 0; /* local buffer length */ char *p, line[MAXLEN]; nlines = 0; while ((len = my_getline(line, MAXLEN)) > 0) if (nlines >= maxlines || lbl >= LOCALBUFSIZE-1) return -1; else { line[len] = '\0'; p = &lb[lbl]; lptr[nlines++] = p; i = 0; while ((lb[lbl++] = line[i++])) /* strcat doesn't seem to do quite*/ ; /* what I want... but this works */ } return nlines; } int main() { static char localbuf[LOCALBUFSIZE]; int nlines; if ((nlines = readlines(lineptr, localbuf, MAXLINES)) >= 0){ my_qsort(lineptr, 0, nlines-1); writelines(lineptr, nlines); } else { printf("error: input too big to sort\n"); return 1; } return 0; }