Print Alphabetically

Code Id 7
Date Updated 3/7/2010
Title Print alphabetically  
Description
Write a program that reads a series of lines and prints the lines in alphabetical order.

You may assume that there are at most 1000 lines You may assume that each line has at most 1000 characters.
You may assume that the last line of input ends with a newline. 
                                  
Codes Snippet
#include 
#include 

char x[1000][1000];
int xlen[1001];
int y;

/*
Line 0 has xlen[0] bytes: x[0][0], x[0][1], ..., x[0][xlen[0]-1].
Line 1 has xlen[1] bytes: x[1][0], x[1][1], ..., x[1][xlen[1]-1].
Line 2 has xlen[y] bytes: x[2][0], x[2][1], ..., x[2][xlen[2]-1].
...
Line y has xlen[y] bytes: x[y][0], x[y][1], ..., x[y][xlen[y]-1].
That's all the input.
*/

void print(int i) /* print out line i */
{
  int k;

  for (k = 0;k < xlen[i];++k)
    putchar(x[i][k]);
  putchar('n');
}

void copy(int i,int j) /* copy line j to line i */
{
  int k;
  for (k = 0;k < 1000;++k)
    x[i][k] = x[j][k];
  xlen[i] = xlen[j];
}

int smaller(int i,int j) /* is line i alphabetically before line j? */
{
  int k;

  k = 0;
  for (;;) {
    if (k >= xlen[i]) return 1;
    if (k >= xlen[j]) return 0;
    if (tolower(x[i][k]) < tolower(x[j][k])) return 1;
    if (tolower(x[i][k]) > tolower(x[j][k])) return 0;
    ++k;
  }
}

int main(void)
{
  char c;
  int i;
  int smallest;

  xlen[0] = 0;
  y = 0;

  while (scanf("%c",&c) == 1)
    if (c == 'n') {
      if (y < 1000)
        xlen[++y] = 0;
    }
    else
      if (y < 1000)
        if (xlen[y] < 1000)
          x[y][xlen[y]++] = c;

  while (y > 0) {
    smallest = 0;
    for (i = 1;i < y;++i)
      if (smaller(i,smallest))
        smallest = i;
    print(smallest);
    copy(smallest,--y);
  }

  return 0;
}

Comments are closed.