Sunday, August 26, 2012

Exercise 5-7

My solution for Exercise 5-7
THE C PROGRAMMING LANGUAGE, 2nd ed.
Kernighan and Ritchie


#include <stdio.h>
#include <string.h>

#define MAXLINES 5000   /* max # of lines to be stored */
#define BUFFERSIZE 1000000 /* */

char *lineptr[MAXLINES];    /* pointers to text lines */

int readlines(char *[], int, char []);
void writelines(char *[], int);
void qsort(char *[], int, int);

/* sort input lines */
int main()
{
    int nlines;     /* number of input lines read */
    char buffer[BUFFERSIZE];    /* instead of allocbuf */

    printf("To finish input, hit Enter, then EOF (Ctrl+z for Windows or Ctrl+d for Linux), then hit Enter again.\n");
    if ((nlines = readlines(lineptr, MAXLINES, buffer)) >= 0) {
        qsort(lineptr, 0, nlines-1);
        writelines(lineptr, nlines);
        return 0;
    } else {
        printf("error: input too big to sort\n");
        return 1;
    }
}

#define MAXLEN 1000 /* max length of any input line */
int getline(char *, int);
int mystrcmp(char *, char *);
void swap2(char *v[], int i, int j);

/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines, char buffer[])
{
int len, nlines;
char *p, line[MAXLEN];
char *bufferp = buffer;

nlines = 0;
while ((len = getline(line, MAXLEN)) > 0) {
        if (buffer + BUFFERSIZE - bufferp >= len && nlines < maxlines) {
            line[len-1] = '\0'; /* delete newline */
            strcpy(bufferp, line);  /* store line in buffer */
            lineptr[nlines++] = bufferp;
            bufferp += len;
        } else {
            return -1;
        }
}
return nlines;
}

/* writelines: write output lines */
void writelines(char *lineptr[], int nlines)
{
int i;
    printf("------- writelines -------\n");
for (i = 0; i < nlines; i++)
printf("%s\n", lineptr[i]);
}

/* getline: read a line into s including newline, return length,
   lim = max length of any input line */
int getline(char s[], int lim)
{
    int c, i;

    for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

/* qsort: sort v[left]...v[right] into increasing order */
void qsort(char *v[], int left, int right)
{
    int i, last;

    if (left >= right)
        return;
    swap2(v, left, (left + right)/2);
    last = left;
    for (i = left+1; i <= right; i++)
        if (mystrcmp(v[i], v[left]) < 0)
            swap2(v, ++last, i);
    swap2(v, left, last);
    qsort(v, left, last-1);
    qsort(v, last+1, right);
}

/* swap2: interchange v[i] and v[j] */
void swap2(char *v[], int i, int j)
{
    char *temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

/* strcmp: return < 0 if s < t, 0 if s == t, > 0 if s > t */
int mystrcmp(char *s, char *t)
{
    int i;

    for (i = 0; s[i] == t[i]; i++)
        if (s[i] == '\0')
            return 0;
        return s[i] - t[i];
}

-unkokusei

No comments:

Post a Comment