/* * ===================================================================== * bubble1.c -- Basic bubble sorting algorithm for character strings * * Copyright (C) 1993-96 by Mark Austin and David Mazzoni. * * This software is provided "as is" without express or implied warranty. * Permission is granted to use this software on any computer system, * and to redistribute it freely, subject to the following restrictions: * * 1. The authors are not responsible for the consequences of use of * this software, even if they arise from defects in the software. * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * 4. This notice is to remain intact. * ===================================================================== */ #include #include #define VERBOSE int main( void ) { char * cpaList[] = { "this", "is", "the", "list", "of", "words", "to", "be", "sorted" }; char * cpTemp; int iInner, iOuter; /* counters for loops while sorting */ int iSize, iLine; /* for printing the list */ /* [a] : Bubble sort contents of cpaList[] */ iOuter = iSize = sizeof( cpaList ) / sizeof( cpaList[0] ); #ifdef VERBOSE for( iLine = 0; iLine < iSize; iLine++ ) printf( "cpaList[%2d] = %s\n", iLine, cpaList[iLine] ); #endif while( iOuter >= 1 ) { /* there are still elements to compare */ iInner = 1; while( iInner <= iOuter-1 ) { #ifdef VERBOSE printf(" iInner = %3d iOuter = %3d\n", iInner, iOuter); #endif if( strcmp( cpaList[iInner - 1], cpaList[iInner]) > 0 ) { /* swap the values using the iTempVal as an intermediate */ cpTemp = cpaList[iInner]; cpaList[iInner] = cpaList[iInner-1]; cpaList[iInner-1] = cpTemp; #ifdef VERBOSE printf("\n"); for( iLine = 0; iLine < iSize; iLine++ ) printf( "cpaList[%2d] = %s\n", iLine, cpaList[iLine] ); #endif } iInner = iInner + 1; /* compare the next two array elements */ } iOuter = iOuter - 1; } /* [b] : Print contents of sorted list */ for( iLine = 0; iLine < iSize; iLine++ ) printf( "cpaList[%2d] = %s\n", iLine, cpaList[iLine] ); }