(Sorting strings) Write a version of the selection sort routine (Fig. 8.28) that sorts strings. Use function swap in your solution.
What will be an ideal response?
```
#include
#include
using namespace std;
// prototypes
void output( const string *, const int );
void selectionSort( string [], const int );
void swap( string * const, string * const );
int main()
{
const int SIZE = 19;
string animals[ SIZE ] = { "Macaw", "Lion", "Tiger", "Bear", "Toucan",
"Zebra", "Puma", "Cat", "Yak", "Boar", "Fox", "Ferret",
"Crocodile", "Alligator", "Elk", "Ox", "Horse", "Eagle", "Hawk" };
cout << "before:";
output( animals, SIZE );
selectionSort( animals, SIZE ); // sort string
cout << "\nafter:";
output( animals, SIZE );
} // end main
// function output to print array of animal names
void output( const string * ani, const int length )
{
for ( int j = 0; j < length; j++ )
cout << ( j % 10 ? ' ': '\n' ) << ani[ j ];
cout << endl;
} // end function output
// function to sort array
void selectionSort( string animals[], const int size )
{
int smallest; // index of smallest element
// loop over size - 1 elements
for ( int i = 0; i < size - 1; i++ )
{
smallest = i; // first index of remaining vector
// loop to find index of smallest (or largest) element
for ( int index = i + 1; index < size; index++ )
if ( animals[ smallest ] > animals[ index ] )
smallest = index;
swap( &animals[ smallest ], &animals[ i ] );
} // end if
} // end function selectionSort
// swap values at memory locations to which
// element1Ptr and element2Ptr point
void swap( string * const element1Ptr, string * const element2Ptr )
{
string hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
} // end function swap
```
before:
Macaw Lion Tiger Bear Toucan Zebra Puma Cat Yak Boar
Fox Ferret Crocodile Alligator Elk Ox Horse Eagle Hawk
after:
Alligator Bear Boar Cat Crocodile Eagle Elk Ferret Fox Hawk
Horse Lion Macaw Ox Puma Tiger Toucan Yak Zebra
You might also like to view...
On a network, data transfer rate is measured by megabits per second, where a megabit represents one billion bits
Indicate whether the statement is true or false
Which of the following is the MAXIMUM transfer speed of USB 2.0?
A. 100 Mbps B. 400 Mbps C. 420 Mbps D. 480 Mbps