/* Name: pmsort.c Purpose: "Poor man's" sort utility Author: Bill Slough Usage: pmsort filename */ #include #include #include #include #include "util.h" void sort(char *v[ ], int n); void swap(char **p, char **q); int main(int argc, char *argv[ ]) { FILE *fp; /* file pointer for an input stream */ char **lines; /* NULL-terminated array of strings */ int nrLines; /* number of lines in the lines array */ /* Check for proper usage */ if (argc != 2) { fprintf(stderr, "Usage: pmsort filename\n"); exit(EXIT_FAILURE); } /* Try to open the input stream for reading */ fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(stderr, "Error: can't open \"%s\" for reading.\n", argv[1]); exit(EXIT_FAILURE); } /* Read and store the lines */ lines = read_lines(fp); nrLines = count_lines(lines); /* Process */ sort(lines, nrLines); display_lines(lines); /* Close the stream */ fclose(fp); return 0; } /* sort an array of n strings into lexicographical order */ void sort(char *v[ ], int n) { int i; int j; int k; /* use selection sort to rearrange the strings in sorted order */ i = 0; while (i < n - 1) { /* v[0], v[1], v[2], ..., v[i - 1] are in sorted order and they are the smallest among all the elements in v. To make progress, locate the smallest value in the tail end of v and place it at v[i] */ j = i; /* index of smallest known element among v[i] ... v[n - 1] */ for (k = i + 1; k < n; k++) { /* is there a smaller value somewhere? */ if (strcmp(v[k], v[j]) < 0) j = k; } swap(&v[i], &v[j]); i++; } } /* swap two strings in an array of strings */ void swap(char **p, char **q) { char *temp; temp = *p; *p = *q; *q = temp; }