/* strSort.cpp * * Sample string sorting program * * Bruce M. Bolden * November 18, 1997 * * http://www.cs.uidaho.edu/~bruceb/ * --------------------------------------------------------- */ #include #include #include #include #include #include // for g++ const int FALSE = 0; const int TRUE = 1; const int MAX_NAME = 20; // function prototypes void ShowNameArray( const char names[][MAX_NAME], const int nNames ); void SortNameArray( char names[][MAX_NAME], const int nNames ); void SwapString( char *s1, char *s2 ); int SearchNameArray( const char *name, const char names[][MAX_NAME], const int nMax ); void ShowNameSearchResult( const char *aName, const int i ); main() { const int nArtists = 7; char artists[nArtists][MAX_NAME] = { "Beach Boys", "Who", "Gershwin", "Chicago", "Led Zeppelin", "Yes", "ZZ Top" }; cout << "Array contents before sorting:\n" << endl; ShowNameArray( artists, nArtists ); SortNameArray( artists, nArtists ); cout << "Array contents after sorting:\n" << endl; ShowNameArray( artists, nArtists ); // Do a little searching.... cout << "\nSearching:\n" << endl; int iFound; // Index returned by search operation char *search[3] = { "Beatles", "Who", "Gershwin" }; for( int i = 0 ; i < 3 ; ++i ) { iFound = SearchNameArray( search[i], artists, nArtists ); ShowNameSearchResult( search[i], iFound ); } return 0; } /* ShowNameArray * * Show the contents of an array of character pointers */ void ShowNameArray( const char names[][MAX_NAME], const int nNames ) { for( int i = 0 ; i < nNames ; i++ ) { cout << names[i] << endl; } } /* SortNameArray * * Perform a bubble sort on an array of character pointers. */ void SortNameArray( char names[][MAX_NAME], const int nNames ) { int swapFlag = TRUE; for( int i = 0 ; i < nNames && swapFlag == TRUE ; i++ ) { swapFlag = FALSE; for( int j = 0 ; j < nNames - 1 ; j++ ) { if( strcmp(names[j], names[j+1]) > 0 ) // swap them { swapFlag = TRUE; SwapString( names[j], names[j+1] ); } } } } /* SwapString * * Swap two strings. */ void SwapString( char *s1, char *s2 ) { char tmpStr[MAX_NAME]; // longest string strcpy( tmpStr, s1 ); strcpy( s1, s2 ); strcpy( s2, tmpStr ); } /* SearchNameArray * * Searches for the name in the aray of names. * If successful, the index is returned. * If unsuccessful, -1 is returned. */ int SearchNameArray( const char *name, const char names[][MAX_NAME], const int nMax ) { for( int i = 0 ; i < nMax ; i++ ) { if( strcmp( names[i], name) == 0 ) return i; } return -1; } /* ShowNameSearchResult * * Show results of a search for a given string */ void ShowNameSearchResult( const char *name, const int i ) { cout << name; if( i < 0 ) { cout << " not found"; } else { cout << " found at location: " << i; } cout << endl; }