/* Ferworn, Winter 00, 
Example Text Sort 2: a program to sort a file of a most MAX_NUM words into ascending order and
output each unique word in ascending order 

Instead of moving strings around, this manipulates an array of integers "where"
that keeps track of the index numbers of the "words" array. ie. elements in the integer
array points at the elements in the char array */

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

#define FALSE 0
#define TRUE 1
#define MAX_SIZE 20
#define MAX_NUM 1000

int input(char [MAX_NUM][MAX_SIZE]);
void bubble_sort(char [MAX_NUM][MAX_SIZE],int [MAX_NUM],int);
void output(char [MAX_NUM][MAX_SIZE],int [MAX_NUM], int);
void init_where(int [MAX_NUM], int);

void main()
{
	char words[MAX_NUM][MAX_SIZE];
	int where[MAX_NUM];
	int how_many;

	how_many=input(words);
	init_where(where,how_many);
	output(words,where,how_many);
	bubble_sort(words,where,how_many);
	output(words,where,how_many);
}

void init_where(int where[MAX_NUM], int how_many)
{
	int i;
	for(i=0;i<how_many;i++)
		where[i]=i;
}

int input(char array[MAX_NUM][MAX_SIZE])
{
	int count=0;
	do
	{
		printf("Enter a word (Enter the word ""stop"" to stop): ");
		scanf("%s",array[count]); 
	}
	while(strcmp(array[count++],"stop"));
	return count-1
	;
}

void bubble_sort(char array[MAX_NUM][MAX_SIZE],int where[MAX_NUM],int count)
{
	int j,k,sorted=FALSE;
	int temp;
	while(!sorted)
	{
		sorted = TRUE;
		for(j=0;j<count-1;j++)
		{
			if(strcmp(array[where[j]],array[where[j+1]]) > 0)
			{
				sorted = FALSE;
				temp = where[j];
				where[j] = where[j+1];
				where[j+1] = temp;
			}
		}
    }
}

void output(char array[MAX_NUM][MAX_SIZE],int where[MAX_NUM],int count)
{
	int i;
	for(i=0;i<count;i++)
		printf("%s ",array[where[i]]);
	printf("\n\n");
}