Section 4 - Sorting String Arrays

8A.4.1 Nothing Really New

All I want to do here is revise the sorting application we just learned so that it can sort an array of strings instead of ints.  To do that we have to know how to ask the question is string1 < string2, that is, does string1 come before string2 in alphabetical ordering.  For that we use the string instance method compare().

string1.compare( string2 )

Returns a 0 if they are equal, a negative number if string1 comes before string2 and a positive number if string1 comes after string2. So instead of asking whether

data[k] > data[k+1]

we ask the question:

data[k].compare(data[k+1]) > 0

And with that one change, we can change the program so it works for strings.  The output would look like this:

console shot

Here is the program with the small modifications to work with Strings.

#include <string>
#include <iostream>
using namespace std;

// method prototypes
bool floatLargestToTop(string data[], int arraySize);
void printArray(string title, string data[], int arraySize);
void arraySort(string array[], int arraySize);
void mySwap(string &a, string &b);

int main ()
{
string myArray[] = {"you", "me", "them", "us", "him",
"her", "he", "she"};

// compute the size of the array
short arraySize = sizeof(myArray)/sizeof(myArray[0]);

printArray("Before: ", myArray, arraySize);
arraySort(myArray, arraySize);
printArray("After: ", myArray, arraySize);
}

// returns true if a modification was made to the array
bool floatLargestToTop(string data[], int top)
{
bool changed = false;

for (int k = 0; k < top; k++)
if (data[k].compare(data[k+1]) > 0)
{
mySwap(data[k], data[k+1]);
changed = true;
}
return changed;
}

// print out the array with the string as a title for the message box
void printArray(string title, string data[], int arraySize)
{
cout << title << "  ";

for (int k = 0; k < arraySize; k++)
{
cout << data[k] << "   ";
// every fifth string, print newline
if (k%5 == 4)
cout << endl;
}
cout << endl;

}

void arraySort(string array[], int arraySize)
{
int everShrinkingTop;

for (   everShrinkingTop = arraySize - 1;
everShrinkingTop > 0;
everShrinkingTop--
)
if ( !floatLargestToTop(array, everShrinkingTop) )
return;
}

void mySwap(string &a, string &b)
{
string temp;

temp = a;
a = b;
b = temp;
}

See? I told you: three minutes.