Bsort.c

/* A bubble-sort demonstration */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Prototypes, though they aren't needed in this example, because 
** of the order of the functions
*/
void InitData( char * List[], short Count );
void BubbleSort( char *Lines[] );
void Print( char * Lines[] );
void Free( char * Lines[] );

#define MAX 21

/* Example data, to be sorted */
char *Data[ MAX+1];

/* This routine initializes the example data with random information */
void InitData( char * List[], short Count )
{
	char Temp[6];
	short i;

	Count--;
	for( i=0; i < Count; i++ )
	{
		sprintf(Temp, "%05u", rand() );
		if( (Data[i]=strdup( Temp )) == NULL )
		{
			perror( "Out of memory" );
			exit(1);
		}
	}
	List[i] = NULL; /* NULL Pointer used as a terminator */
}

/***********************************************************
** Name:	BubbleSort
** Descr:	Sorts an array of string pointers, using a bubble-sort technique
** Params:	Lines = Arrray of pointers to be sorted
** Author:	MG 9/16/97
** Comment:	Note how the Swap flag is used to terminate the loop if the data
**          becomes sorted early.  This is a benefit to this particular sort 
**          technique.
***********************************************************/
void BubbleSort( char *Lines[] )
{
	unsigned short Inner, Swap=1, Count;
	char *Tmp;

	for( Count=0; Lines[Count]; Count++ ) /* Count elements in the array */
		;
	
	if( Count==0 )	/* Nothing to sort */
		return;
	
	while( Swap && Count-- ) /* This is the outter loop */
	{
		/* The inner loop */
		for( Inner=Swap=0; Inner < Count; Inner++ )
		{
			if( stricmp( Lines[Inner], Lines[Inner+1] ) > 0 ) /* Compare strings */
			{
				Tmp=Lines[Inner];
				Lines[Inner]=Lines[Inner+1];
				Lines[Inner+1]=Tmp;
				Swap=1;
			}
		}
	}

}

/* Displays the strings in an array */
void Print( char * Lines[] )
{
	while( *Lines )
		printf("%s\n", *Lines++ );
}

/* Removes the lines from memory, and the array itself */
void Free( char * Lines[] )
{
	int i;
	for( i=0; Lines[i]; i++ )
		free( Lines[i] );
}

void main( void )
{
	InitData( Data, MAX );
	BubbleSort( Data );
	Print( Data );
	Free( Data );
	exit(0);
}