Program: Bubble Sort (with workings)



Code below:


// Bubble Sort - Phil Gardner

#include <iostream>    // Program will display some text on the screen as output

using namespace std;    // Will be using standard identifiers string, cout and endl

// --------------------

void displayArray( string value[], int numItems )
{
    for ( int index = 0;  index < numItems;  index++ )
        cout << "\tItem no. " << index << " is " << value[index] << endl;
    cout << "- - - - - - - - - -" << endl;
}

// --------------------

void sortArray( string value[], int numItems )
{
    string tempValue;    // Used when swapping a pair of data values with each other
    int passNumber = 1;

    bool performedASwap;

    do
    {
        performedASwap = false;

        for ( int index = 0;  index < numItems-1;  index++ )
        {

            if ( value[index] > value[index+1] )
            {
                // Swap the pair of items around (via the temporary variable)
                tempValue = value[index];
                value[index] = value[index+1];
                value[index+1] = tempValue;

                performedASwap = true;
            }  // end of if decision that performs a swap

        }  // end of for loop that performs one whole pass through the array

        // Display current progress after a complete pass through the data
        cout << "After pass " << passNumber << endl;
        displayArray( value, numItems );
        passNumber = passNumber + 1;

    } while ( performedASwap );  // Keeps repeating passes until no swaps made

}

// --------------------

int main()
{
    // Create an array of data that will be sorted and displayed
    const int NUM_ITEMS = 5;
    string cityName[ NUM_ITEMS ];

    cityName[0] = "Chicago";
    cityName[1] = "New York";
    cityName[2] = "San Francisco";
    cityName[3] = "Detroit";
    cityName[4] = "Miami";

    // Call the displayArray function to display the array called cityName
    cout << "BEFORE sorting, the array looks like this..." << endl;
    displayArray( cityName, NUM_ITEMS );

    // Call the sortArray function to sort the itmes in the array called cityName
    sortArray( cityName, NUM_ITEMS );

    // Call the displayArray function again to display the updated cityName array
    cout << "BUBBLE-SORT COMPLETE. GO HOME." << endl;

    return 0;
}