Friday, March 10, 2017

Programming Challenge 8.11 - Using Files - String Selection Sort Modification

Example File: names.txt

/* Using Files - String Selection Sort Modification - This program is
   a modification of Programming Challenge 8.6. It reads in 20 strings
   from the file "names.txt" and sorts them. */

#include "Utility.h"

int getFile(string[], const int);
void selectionSort(string[], const int);
void displayUnsorted(const string[], const int);
void displaySorted(const string[], const int);

int main()
{
   const int NUM_NAMES = 20;
  
   int returnCode = 0;

   string names[NUM_NAMES] = { " " };

   /* Gets and stores the names stored in "names.txt" */
   returnCode = getFile(names, NUM_NAMES);

   if (returnCode != -1)
   {
      /* Displays the unsorted names list */
      displayUnsorted(names, NUM_NAMES);

      /* Sorts the names with selection sort */
      selectionSort(names, NUM_NAMES);

      /* Displays the sorted name list */
      displaySorted(names, NUM_NAMES);
   }

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getFile

   This function accepts names and NUMELS, containing the
   number of elements in the array, as arguments. If opened
   successfully, the content of the file "names.txt" will be
   stored in names. In case of a file processing error, an
   error message is displayed, and the program will exit.
   ********************************************************** */

int getFile(string names[], const int NUMELS)
{
   ifstream getNames;
  
   int count = 0;

   getNames.open("names.txt");

   if (getNames)
   {
      while (count < NUMELS && !getNames.eof())
      {
         getline(getNames, names[count]);

         count++;
      }
   }
   else
   {
      cout << "\nFile open error: The file 'names.txt' could not\n"
           << "be opened or processed. Please make sure that the filename is\n"
           << "correct and the file is not damaged or has been moved from the\n"
           << "program folder. Please close this program now and try again ...\n\n";

      return -1;
   }

   getNames.close();

   return 0;
}

/* **********************************************************
   Definition: displayUnsorted

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It displays the unsorted name list stored in names.
   ********************************************************** */

void displayUnsorted(const string names[], const int NUMELS)
{
   cout << "\n\tUNSORTED NAME-LIST\n\n";

   for (int index = 0; index < NUMELS; index++)
   {
      cout << "\t" << names[index] << " \n";
   }
   cout << "\n";
}

   /* **********************************************************
   Definition: selectionSort

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It uses election sort algorithm is used to sort the names
   in alphabetical order.
   ********************************************************** */

void selectionSort(string names[], const int NUM_NAMES)
{
   int startScan = 0,
       minIndex = 0,
       index = 0;

   string minAlpha = " ";

   for (startScan = 0; startScan < (NUM_NAMES - 1); startScan++)
   {
      minIndex = startScan;
      minAlpha = names[startScan];

      for (index = startScan + 1; index < NUM_NAMES; index++)
      {

         if (names[index] < minAlpha)
         {
            minAlpha = names[index];
            minIndex = index;
         }
      }

      names[minIndex] = names[startScan];
      names[startScan] = minAlpha;
   }         
}

/* **********************************************************
   Definition: displaySorted

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It displays the names in ascending alphabetic order.
   ********************************************************** */

void displaySorted(const string names[], const int NUMELS)
{
   cout << "\n\tSORTED NAME-LIST\n\n";

   for (int index = 0; index < NUMELS; index++)
   {
      cout << "\t" << names[index] << " \n";
   }
   cout << "\n";
}

Example Output:




Programming Challenge 8.10 - Sorting Orders

/* Sorting Orders - This program uses two identical arrays of just eight
   integers. It displays the contents of the first array, then calls a
   function to sort the array using an ascending order bubble sort modified
   to print out the array contents after each pass of the sort. Next, the
   program displays the contents of the second array, then calls a function
   to sort the array using an ascending order selection sort modified to
   print out the array contents after each pass of the sort. */

#include "Utility.h"

void displayUnsorted(const int[], const int);
void bubbleSortAlg(int[], const int);
void selectionSortAlg(int[], const int);

int main()
{
   const int NUMELS = 8;

   int bubbleSort[NUMELS] = { 4, 8, 5, 3, 1, 2, 7, 6 };
   int selectionSort[NUMELS] = { 4, 8, 5, 3, 1, 2, 7, 6 };
 
   /* First the arrays are displayed, then the numbers are sorted,
   and the sorting process is displayed (bubble sort comes first,
   followed by selection sort) */
   cout << "\n\t\t BUBBLE SORT\n\n";

   displayUnsorted(bubbleSort, NUMELS);
   bubbleSortAlg(bubbleSort, NUMELS);

   cout << "\n\n\n\t\t SELECTION SORT\n\n";

   displayUnsorted(selectionSort, NUMELS);
   selectionSortAlg(selectionSort, NUMELS);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: displayUnsorted

   This function accepts bubbleSort, selectionSort and NUMELS
   containing the size of the arrays contents, as arguments.
   It displays the unsorted array, one after the other.
   ********************************************************** */

void displayUnsorted(const int unsortedArray[], const int NUMELS)
{
   cout << "\t\t UNSORTED LIST\n\n";

   cout << "\t\t";
   for (int index = 0; index < NUMELS; index++)
   {
      cout << " " << unsortedArray[index] << " ";
   }
   cout << "\n";
}

/* **********************************************************
   Definition: bubbleSortAlg

   This function accepts bubbleSort and NUMELS containing the
   number of elements in the array as arguments. After each
   sorting pass the content of the array is displayed.
   ********************************************************** */

void bubbleSortAlg(int bubbleSort[], const int NUMELS)
{
   int temp = 0,
       count = 0;

   bool swap = false;

   do
   {
      swap = false;

      for (count = 0; count < (NUMELS - 1); count++)
      {

         if (bubbleSort[count] > bubbleSort[count + 1])
         {
            temp = bubbleSort[count];
            bubbleSort[count] = bubbleSort[count + 1];
            bubbleSort[count + 1] = temp;
            swap = true;

            cout << "\n\t\t";
            for (count = 0; count < NUMELS; count++)
            {
               cout << " " << bubbleSort[count] << " ";
            }      
           }  
      }
   } while (swap);
}

/* **********************************************************
   Definition: selectionSortAlg

   This function accepts selectionSort and NUMELS containing
   the size of the array as arguments.
   While the numbers are sorted, the content of bubbleSort is
   displayed after each sorting pass.
   ********************************************************** */

void selectionSortAlg(int selectionSort[], const int NUMELS)
{
   int startScan = 0,
      minIndex = 0,
      minValue = 0,
      index = 0,
      swapCount = 0;

   bool swap = false;

   for (startScan = 0; startScan < NUMELS - 1; startScan++)
   {
      swap = false;

      minIndex = startScan;
      minValue = selectionSort[startScan];

      for (index = startScan + 1; index < NUMELS; index++)
      {
         if (selectionSort[index] < minValue)
         {
            minValue = selectionSort[index];
            minIndex = index;
            swap = true;
         }
      }

      cout << "\n\t\t";
      for (index = 0; index < NUMELS; index++)
      {
         cout << " " << selectionSort[index] << " ";
      }

      selectionSort[minIndex] = selectionSort[startScan];
      selectionSort[startScan] = minValue;
   }
}

Example Output:



Programming Challenge 8.9 - Sorting Benchmarks

Example Files: bubbleSort.txt
                         selectionSort.txt
                         
Info: To get a list of random numbers for your own tests please visit: random.org
/* Sorting Benchmarks - This program uses two identical arrayys of at
   least 20 integers. It calls a function that uses the bubble sort
   algorithm to sort one of the arrays in ascending order. The function
   keeps a count of the number of exchanges it makes. The program then
   calls a function that uses the selection sort algorithm to sort the
   other array. It keeps a count of the number of exchanges it makes.
   The values are displayed on the screen. */

#include "Utility.h"

/* Function prototypes */
int getFileBSort(int[], int);
int bubbleSortAlg(int[], const int);
void displaySorted(const int[], const int[], const int);
void displayUnsorted(const int[], const int[], const int);
int getFileSSort(int[], int);
int selectionSortAlg(int[], int);
void displayComparison(const int, const int, const int);

int main()
{
   const int SORT_NUMELS = 20;

   /* These arrays hold the numbers stored in "bubbleSort.txt"
      and "selectionSort.txt" */
   int bubbleSort[SORT_NUMELS] = { };
   int selectionSort[SORT_NUMELS] = { };

   int returnCode = 0,
       numSwapsBSort = 0,
       numSwapsSSort = 0;

   /* Get and store the numbers in bubbleSort */
   returnCode = getFileBSort(bubbleSort, SORT_NUMELS);

   /* If returnCode is not -1 after opening and processing "bubbleSort.txt",
      "selectionSort.txt" is tried next. */
   if (returnCode != -1)
   {
      /* Get and store the numbers in selectionSort */
      returnCode = getFileSSort(selectionSort, SORT_NUMELS);

      /* If opening "selectionSort.txt" fails, an error message is displayed,
         and the following code-block will not be processed. */
      if (returnCode != -1)
      {
         /* Displays the unsorted list of numbers contained in both arrays */
         displayUnsorted(bubbleSort, selectionSort, SORT_NUMELS);

         /* Sorts the numbers and returns the number of swaps it has taken */
         numSwapsBSort = bubbleSortAlg(bubbleSort, SORT_NUMELS);

         /* Sorts the numbers and returns the number of swaps it has taken */
         numSwapsSSort = selectionSortAlg(selectionSort, SORT_NUMELS);
        
         /* Displays the sorted numbers contained in both arrays */
         displaySorted(bubbleSort, selectionSort, SORT_NUMELS);

         /* Displays a comparison in the number of swaps between bubble and
            selection sort */
         displayComparison(numSwapsBSort, numSwapsSSort, SORT_NUMELS);
      }
   }

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getFileBSort

   This function accepts bubbleSort and SORT_NUMELS as
   its arguments. It processes the content of the file
   "bubbleSort.txt". If the file is opened successfully,
   the numbers are read-in and stored in selectionSort. If
   a file processing error occurs, a message is displayed,
   and the function exits with return code -1.
   ********************************************************** */

int getFileBSort(int bubbleSort[], int SORT_NUMELS)
{
   int count = 0;

   ifstream readNums;

      readNums.open("bubbleSort.txt");

   if (readNums)
   {
      while (count < SORT_NUMELS && !readNums.eof())
      {
         readNums >> bubbleSort[count];

         count++;
      }
   }
   else
   {
      cout << "\nFile open error: The file 'bubbleSort.txt' could not\n"
           << "be opened or processed. Please make sure that the filename is\n"
           << "correct and the file is not damaged or has been moved from the\n"
           << "program folder. Please close this program now and try again ...\n\n";

      return -1;
   }

   readNums.close();


   return 0;
}

/* **********************************************************
   Definition: displayUnsorted

   This function accepts bubbleSort, selectionSort and
   SORT_NUMELS as its arguments. It displays the unsorted
   list of numbers contained in both arrays.
   ********************************************************** */

void displayUnsorted(const int bubbleSort[], const int selectionSort[],
                     const int SORT_NUMELS)
{
   cout << "\n\t\tBUBBLE SORT - UNSORTED LIST\n";

   for (int index = 0; index < SORT_NUMELS; index++)
   {
      /* This if statement adds a newline in case of sorted
      lists equal to or above 50 elements */
      if (index % 25 == 0)
      {
         cout << "\n\t";
      }
      cout << bubbleSort[index] << " ";
   }
   cout << "\n";

   cout << "\n\t\tSELECTION SORT - UNSORTED LIST\n";

   for (int index = 0; index < SORT_NUMELS; index++)
   {
      if (index % 25 == 0)
      {
         cout << "\n\t";
      }
      cout << selectionSort[index] << " ";
   }
   cout << "\n";

}

/* **********************************************************
   Definition: bubbleSortAlg

   This function accepts bubbleSort and SORT_NUMELS as its
   arguments. SORT_NUMELS contains the number of elements
   stored in the array. It sorts the numbers stored in the
   file "bubbleSort.txt" and keeps count of the number of
   swaps it takes to sort the array, and returns this value.
   ********************************************************** */

int bubbleSortAlg(int bubbleSort[], int SORT_NUMELS)
{
   int temp = 0,
       count = 0,
       swapCount = 0;

   bool swap = false;

   do
   {
      swap = false;

      for (int count = 0; count < (SORT_NUMELS - 1); count++)
      {
         if (bubbleSort[count] > bubbleSort[count + 1])
         {
            temp = bubbleSort[count];
            bubbleSort[count] = bubbleSort[count + 1];
            bubbleSort[count + 1] = temp;
            ++swapCount;

            swap = true;
         }
      }
   } while (swap);

   return swapCount;
}

/* **********************************************************
   Definition: getFileSSort

   This function accepts selectionSort and SORT_NUMELS as
   its arguments. It processes the content of the file
   "selectionSort.txt". If the file is opened successfully,
   the numbers are read-in and stored in selectionSort. If
   a file processing error occurs, a message is displayed,
   and the function exits with return code -1.
   ********************************************************** */

int getFileSSort(int selectionSort[], int SORT_NUMELS)
{
   int count = 0;

   ifstream readNums;

   readNums.open("selectionSort.txt");

   if (readNums)
   {
      while (count < SORT_NUMELS && !readNums.eof())
      {
         readNums >> selectionSort[count];

         count++;
      }
   }
   else
   {
      cout << "\nFile open error: The file 'selectionSort.txt' could not\n"
         << "be opened or processed. Please make sure that the filename is\n"
         << "correct and the file is not damaged or has been moved from the\n"
         << "program folder. Please close this program now and try again ...\n\n";

      return -1;
   }

   readNums.close();

   return 0;
}

/* **********************************************************
   Definition: selectionSortAlg

   This function accepts selectionSort and SORT_NUMELS as
   its arguments. SORT_NUMELS contains the number of
   elements stored in the array. It sorts the numbers stored
   in the file "selectionSort.txt" and keeps count of the
   number of swaps it takes to sort the array, and returns
   this value.
   ********************************************************** */

int selectionSortAlg(int selectionSort[], int SORT_NUMELS)
{
   int startScan = 0,
       minIndex = 0,
       minValue = 0,
       index = 0,
       swapCount = 0;

   bool swap = false;

   for (startScan = 0; startScan < SORT_NUMELS - 1; startScan++)
   {
      swap = false;

      minIndex = startScan;
      minValue = selectionSort[startScan];

      for (index = startScan + 1; index < SORT_NUMELS; index++)
      {
         if (selectionSort[index] < minValue)
         {  
            minValue = selectionSort[index];
            minIndex = index;  
            swap = true;
         }      
      }

      selectionSort[minIndex] = selectionSort[startScan];
      selectionSort[startScan] = minValue;
    
      if (swap == true)
      {
         swapCount += 1;
      }
   }

   return swapCount;
}

/* **********************************************************
   Definition: displaySorted

   This function accepts bubbleSort, selectionSort and
   SORT_NUMELS holding the number of elements in the arrays
   as its arguments. It displays the sorted list of n-numbers
   contained in the arrays in sorted order.
   ********************************************************** */

void displaySorted(const int bubbleSort[], const int selectionSort[],
                   const int SORT_NUMELS)
{
   cout << "\n\t\tBUBBLE SORT - SORTED LIST\n";

   for (int index = 0; index < SORT_NUMELS; index++)
   {
      /* This if statement adds a newline in case of sorted
      lists equal to or above 50 elements */
      if (index % 25 == 0)
      {
         cout << "\n\t";
      }
      cout << bubbleSort[index] << " ";
   }
   cout << "\n";

   cout << "\n\t\tSELECTION SORT - SORTED LIST\n";

   for (int index = 0; index < SORT_NUMELS; index++)
   {
      if (index % 25 == 0)
      {
         cout << "\n\t";
      }
      cout << selectionSort[index] << " ";
   }
   cout << "\n";
}

/* **********************************************************
   Definition: displayComparison

   This function accepts bubbleSort, selectionSort and
   SORT_NUMELS holding the number of elements in the arrays
   as its arguments. It displays the number of swaps it has
   taken bubble sort and selection sort to sort a list of
   n-numbers.
   ********************************************************** */

void displayComparison(const int numSwapsBSort, const int numSwapsSSort,
                       const int SORT_NUMELS)
{
   cout << "\n\n\t\t\t  NUMBER OF SWAPS:\n"
        << "\t\t\t     " << SORT_NUMELS << " NUMBERS\n\n"
        << "\t\tBUBBLE SORT" << "\t\t" << "SELECTION SORT\n"
        << "\t\t-----------" << "\t\t" << "--------------\n";
   cout << "\t\t" << numSwapsBSort << "\t\t\t" << numSwapsSSort;
}

Example Output: 










Thursday, March 9, 2017

Programming Challenge 8.8 - Search Benchmarks

Example file: searchNumbers.txt

/* Search Benchmarks - This program has an array of at least 20 integers.
   It calls a function that uses the linear search algorithm to locate
   one of the values. The function keeps a count of the number of
   comparisons it makes until it finds the value. The program then calls
   a function that uses the binary search algorithm to locate the same
   value. It also keeps count of the number of comparisons to make. These
   values are displayed on the screen. */

#include "Utility.h"

int getNumbers(int[], int);
int linearSearch(const int[], int, int);
void sortNumbers(int[], int);
int binarySearch(const int[], const int, const int);
void displaySorted(const int[], const int);
void displayComparison(const int, const int, const int);

int main()
{
   const int NUMELS = 100;
  
   int userNum = 0,
       numCyclesLinear = 0,
       numCyclesBinary = 0,
       returnCode = 0;

   char again = ' ';

   /* Array holding the numbers */
   int numbers[NUMELS] = { };

   /* Gets the numbers stored in "numbers.txt" */
   returnCode = getNumbers(numbers, NUMELS);

   if (returnCode == 0)
   {
      /* Performs a selection sort on numbers */
      sortNumbers(numbers, NUMELS);

      /* Displays the sorted list of numbers */
      displaySorted(numbers, NUMELS);

      do
      {
         cout << "\n\tEnter a number to search for: ";
         cin >> userNum;

         /* Performs a selection sort on numbers */
         sortNumbers(numbers, NUMELS);

         /* Gets the result of the linear and binary search */
         numCyclesLinear = linearSearch(numbers, userNum, NUMELS);
         numCyclesBinary = binarySearch(numbers, userNum, NUMELS);

         /* Displays a comparison between the search algorithms */
         displayComparison(userNum, numCyclesLinear, numCyclesBinary);

         cout << "\n\tDo you wish to try again (y/Y) ? ";
         cin >> again;
      } while (!(again == 'N' || again == 'n'));
   }

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getNumbers

   This function accepts numbers and NUMELS containing the
   number of elements in the array as arguments. It reads in
   a list of numbers from "numbers.txt" and stores the values
   in the array.
   ********************************************************** */

int getNumbers(int numbers[], int NUMELS)
{
   ifstream readNums;

   int count = 0;

   readNums.open("numbers.txt");

   if (readNums)
   {
      while (count < NUMELS && !readNums.eof())
      {
         readNums >> numbers[count];
         count++;
      }     
   }
   else
   {
      cout << "\nFile open error: The file 'numbers.txt' could not\n"
           << "be opened or processed. Please make sure that the filename is\n"
           << "correct and the file is not damaged or has been moved from the\n"
           << "program folder. Please close this program now and try again ...\n\n";

      return 1;
   }

   readNums.close();

   return 0;
}

/* **********************************************************
   Definition: linearSearch

   This function accepts numbers and NUMELS containing the
   number of elements in the array as arguments. It performs
   a linear search and keeps track of the number of cycles
   performed to find the value being searched for. If the
   number could not be found, a message is displayed.
   ********************************************************** */

int linearSearch(const int numbers[], int userNum, int NUMELS)
{
   int index = 0,
       numCycles = 0;

   bool numFound = false;

   for (index = 0; index < NUMELS && !numFound; index++)
   {
      if (userNum == numbers[index])
      {
         numFound = true;
      }

      numCycles += 1;
   }

   if (numFound == false)
   {
      cout << "\n\tLinear Search:\n";
      cout << "\n\tThe number " << userNum << " has not been found ...\n"
           << "\tNumber of search cycles: " << numCycles << "\n";
   }

   return numCycles;
}

/* **********************************************************
   Definition: sortNumbers

   This function accepts numbers and NUMELS containing the
   number of elements in the array as arguments. It performs
   an selection sort on numbers in ascending order.
   ********************************************************** */

void sortNumbers(int numbers[], int NUMELS)
{
      int startScan = 0,
          minIndex = 0,
          minValue = 0,
          index = 0;

   for (startScan = 0; startScan < (NUMELS - 1); startScan++)
   {
      minIndex = startScan;
      minValue = numbers[startScan];

      for (index = startScan + 1; index < NUMELS; index++)
      {
         if (numbers[index] < minValue)
         {
            minValue = numbers[index];
            minIndex = index;
         }
      }

      numbers[minIndex] = numbers[startScan];
      numbers[startScan] = minValue;
   }
}

void displaySorted(const int numbers[], int NUMELS)
{
   cout << "\n\t\t\t\t\tLINEAR | BINARY SEARCH - "
        << "PERFORMANCE COMPARISON\n";

   for (int index = 0; index < NUMELS; index++)
   {
      if (index % 25 == 0)
      {
         cout << "\n\t";
      }
      cout << numbers[index] << " ";
   }

   cout << "\n";
}

/* **********************************************************
   Definition: binarySearch

   This function accepts numbers and NUMELS containing the
   number of elements in the array as arguments. It performs
   a binary search to find the number entered in the array
   and keeps track of the number of search-cycles it took to
   find it. If the number could not be found, a message is
   displayed.
   ********************************************************** */

int binarySearch(const int numbers[], const int userNum, int NUMELS)
{
   int firstElem = 0,
       lastElem = NUMELS - 1,
       midpoint = 0,
       numCycles = 0;

   bool numFound = false;

   while (firstElem <= lastElem && !numFound)
   {
      /* Calculate the midpoint */
      midpoint = (firstElem + lastElem) / 2;

      numbers[midpoint] == userNum ? numFound = true :
      numbers[midpoint] > userNum ? lastElem = midpoint - 1 :
                                    firstElem = midpoint + 1;

      numCycles++;
   }

   if (numFound == false)
   {
      cout << "\n\tBinary Search:\n";
      cout << "\n\tThe number " << userNum << " has not been found ...\n"
           << "\tNumber of search cycles: " << numCycles << "\n\n";
   }

   return numCycles;
}

/* **********************************************************
   Definition: displayComparison

   This function displays the numbers of comparisons it has
   taken to find the value for both linear and binary search,
   performed on an array containing n-number of integers.
   ********************************************************** */

void displayComparison(const int userNum, const int numCyclesLinear,
                       const int numCyclesBinary)
{

      cout << "\n\tLinear Search Cycles" << "\t" << "Binary Search Cycles\n"
           << "\t--------------------" << "\t" << "--------------------\n";

      cout << "\t" << numCyclesLinear << "\t\t\t" << numCyclesBinary << "\n";
}


Example Output:






Tuesday, March 7, 2017

Programming Challenge 8.7 - Binary String Search

/* Binary String Search - This program uses a modified version of the
   binary search algorithm presented in chapter 8, so that it searches
   an array of strings instead of an array of integers. */

#include "Utility.h"

string getName();
void selectionSort(string[], int);
void displaySortedList(const string[], int);
void binarySearch(const string[], const string, int);

int main()
{
   const int NUM_NAMES = 20;

   /* Array holding first and last names */
   string names[NUM_NAMES] = { "Collins, Bill", "Smith, Bart", "Allen, Jim",
                               "Griffin, Jim", "Stamey, Marty", "Rose, Geri",
                               "Taylor, Terri", "Johnson, Jill", "Allison, Jeff",
                               "Looney, Joe", "Wolfe, Bill", "James, Jean",
                               "Weaver, Jim", "Pore, Bob", "Rutherford, Greg",
                               "Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
                               "Pike, Gordon", "Holland, Beth" };
   char again = ' ';

   string searchName = " ";

   /* Allows the user to search for names repeatedly */
   do
   {
      /* Gets a name to be searched for */
      searchName = getName();

      /* Performs a selection sort on the array containing
         the list of names */
      selectionSort(names, NUM_NAMES);

      /* Displays the sorted name list */
      //displaySortedList(names, NUM_NAMES);

      /* Searches and displays a message if the name entered exists
         in the names array */
      binarySearch(names, searchName, NUM_NAMES);

      cout << "\n\t\tDo you wish to perform another search? ";
      cin >> again;

      if (again == 'N' || again == 'n')
      {
         cout << "\n\t\tThanks for using our database ...";
      }
   } while (!(again == 'N' || again == 'n'));

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: getName

   This function gets a name from the user to be searched for
   in the array names containing a list of first and last
   names.
   ********************************************************** */

string getName()
{
   string firstName = " ",
          lastName = " ";
   string name = " ";

      cout << "\n\t\tName Search Database\n\n"
         << "\t\tEnter the last followed by the first name of\n"
         << "\t\tthe person you wish to look up in our database.\n"
         << "\t\tEx: Collins Bill\n\n";
      cout << "\t\tEnter a name: ";
  
   cin >> lastName >> firstName;

   return name = (lastName + ", " + firstName);
}

/* **********************************************************
   Definition: selectionSort

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It uses election sort algorithm is used to sort the names
   in alphabetical order.
   ********************************************************** */

void selectionSort(string names[], int NUM_NAMES)
{
   int startScan = 0,
       minIndex = 0,
       index = 0;

   string minAlpha = " ";

   for (startScan = 0; startScan < (NUM_NAMES - 1); startScan++)
   {
      minIndex = startScan;
      minAlpha = names[startScan];

      for (index = startScan + 1; index < NUM_NAMES; index++)
      {

         if (names[index] < minAlpha)
         {
            minAlpha = names[index];
            minIndex = index;
         }
      }

      names[minIndex] = names[startScan];
      names[startScan] = minAlpha;
   }         
}

/* **********************************************************
   Definition: binarySearch

   This function accepts names, searchName, and NUM_NAMES
   containing the number of elements stored in names as its
   arguments. It searches for a name entered by the user in
   the sorted name list. If the name exists, a message is
   displayed informing the user that the name has been found.
   Otherwise a message indicating that the name does is not
   stored in the database is displayed.
   ********************************************************** */

void binarySearch(const string names[], const string searchName,
                  int NUM_NAMES)
{
   int firstElem = 0,
       lastElem = NUM_NAMES - 1,
       midpoint = 0,
       position = - 1;

   bool nameFound = false;

   while (!nameFound && firstElem <= lastElem)
   {
      /* Calculate the midpoint */
      midpoint = (firstElem + lastElem) / 2;

      names[midpoint] == searchName ? nameFound = true, position = midpoint :
      names[midpoint] > searchName ? lastElem = midpoint - 1 :
                                     firstElem = midpoint + 1;
   }

   nameFound ? cout << "\n\t\tThe name " << searchName
                    << " has been found in our database\n" :
               cout << "\n\t\tThe name " << searchName
                    << " could not be found in our database ...\n";
}

/* **********************************************************
   Definition: displaySortedList

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It verifies that the sorting function is working correctly
   by displaying the list of names.
   ********************************************************** */

void displaySortedList(const string names[], int NUM_NAMES)
{
   cout << "\n\t\tName Database - Sorted List:\n\n";

   for (int index = 0; index < NUM_NAMES; index++)
   {
      cout << "\t\t" << names[index] << " \n";
   }
   cout << "\n";
}

Example Output:




Programming Challenge 8.6 - String Selection Sort

/* String Selection Sort - This program uses a modified version of the
   selection sort algorithm presented in chapter 8, so that it sorts
   an array of strings instead of an array of integers. */

#include "Utility.h"

void selectionSort(string[], int);
void displayUnsortedList(const string[], int);
void displaySortedList(const string[], int);


int main()
{
   const int NUM_NAMES = 20;

   /* Array holding first and last names */
   string names[NUM_NAMES] = { "Collins, Bill", "Smith, Bart", "Allen, Jim",
                               "Griffin Jim", "Stamey, Marty", "Rose, Geri",
                               "Taylor, Terri", "Johnson, Jill", "Allison, Jeff",
                               "Looney, Joe", "Wolfe, Bill", "James, Jean",
                               "Weaver, Jim", "Pore, Bob", "Rutherford, Greg",
                               "Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
                               "Pike, Gordon", "Holland, Beth" };

   /* Displays the vanilla name list */
   displayUnsortedList(names, NUM_NAMES);

   /* Sorts the list in alphabetic order */
   selectionSort(names, NUM_NAMES);

   /* Displays the name list in alphabetical order */
   displaySortedList(names, NUM_NAMES);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: selectionSort

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It uses election sort algorithm is used to sort the names
   in alphabetical order.
   ********************************************************** */

void selectionSort(string names[], int NUM_NAMES)
{
   int startScan = 0,
       minIndex = 0,
       index = 0;

   string minAlpha = " ";

   for (startScan = 0; startScan < (NUM_NAMES - 1); startScan++)
   {
      minIndex = startScan;
      minAlpha = names[startScan];

      for (index = startScan + 1; index < NUM_NAMES; index++)
      {

         if (names[index] < minAlpha)
         {
            minAlpha = names[index];
            minIndex = index;
         }
      }

      names[minIndex] = names[startScan];
      names[startScan] = minAlpha;
   }         
}

/* **********************************************************
   Definition: displayUnsortedList

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It displays the list of names in unsorted order.
   ********************************************************** */

void displayUnsortedList(const string names[], int NUM_NAMES)
{
   cout << "\n\t\tName Database - Unsorted List:\n\n";
  
   for (int index = 0; index < NUM_NAMES; index++)
   {
      cout << "\t\t" << names[index] << " \n";
   }
   cout << "\t\t";
}

/* **********************************************************
   Definition: displaySortedList

   This function accepts names and NUM_Names, containing the
   number of elements stored in the array, as its arguments.
   It displays the list of names in alphabetical order.
   ********************************************************** */

void displaySortedList(const string names[], int NUM_NAMES)
{
   cout << "\n\t\tName Database - Sorted List:\n\n";

   for (int index = 0; index < NUM_NAMES; index++)
   {
      cout << "\t\t" << names[index] << " \n";
   }
   cout << "\n";
}

Example Output:


Programming Challenge 8.5 - Rainfall Statistics Modification

/* Rainfall Statistics Modification - This program lets the user enter
   the total rainfall for each of 12 months into an array of doubles.
   The program calculates and displays:
 
      * The total rainfall for the year
      * The average monthly rainfall
      * The months with the highest and lowest amounts
    
   Input validation: No negative numbers are accepted for monthly
   rainfall figures.
 
   This program is a modification of Programming Challenge 7.2. It
   displays a list of months, sorted in order of rainfall, from highest
   to lowest. */

#include "Utility.h"

/* Function prototypes */
void displayHeader();
void getRainfallData(double[], const string[], int);
double getTotalAmount(const double[], int);
double getHighestAmount(const double[], const string[], string &, int);
double getLowestAmount(const double[], const string[], string &, int);
double getAverageAmount(const double[], int);
void displayRainfallData(const double[], const double, const double,
                         const string, const double, const string,
                         const double, int);
void sortRainfallData(double[], string[], int);
void displaySorted(const double[], const string[], int);


int main()
{
   const int NUM_MONTHS = 12;

   /* Array containing month names */
   string monthNames[NUM_MONTHS] = { "January", "February", "March",
                                     "April", "May", "June", "July",
                                     "August", "September", "October",
                                     "November", "December" };

   /* Array to hold the amount of rainfall for each month */
   double rainfall[NUM_MONTHS] = { 0.0 };

   double highestAmount = 0.0,
          lowestAmount = 0.0,
          monthlyAverage = 0.0,
          totalAmount = 0.0;

   string monthHighest = " ",
          monthLowest = " ";

   /* Displays the program header */
   displayHeader();

   /* Gets rainfall data */
   getRainfallData(rainfall, monthNames, NUM_MONTHS);

   /* Calculates the total amount of rainfall */
   totalAmount = getTotalAmount(rainfall, NUM_MONTHS);

   /* Gets month and month name with highest amount of rainfall */
   highestAmount = getHighestAmount(rainfall, monthNames, monthHighest,
                                    NUM_MONTHS);

   /* Gets month and month name with lowest amount of rainfall */
   lowestAmount = getLowestAmount(rainfall, monthNames, monthLowest,
                                  NUM_MONTHS);

   /* Gets the monthly average over a 12 month period */
   monthlyAverage = getAverageAmount(rainfall, NUM_MONTHS);

   /* Displays the data in formatted order */
   displayRainfallData(rainfall, totalAmount, highestAmount, monthHighest,
                       lowestAmount, monthLowest, monthlyAverage, NUM_MONTHS);

   /* Uses selection sort to sort and order rainfall and monthNames */
   sortRainfallData(rainfall, monthNames, NUM_MONTHS);

   /* Displays the sorted list */
   displaySorted(rainfall, monthNames, NUM_MONTHS);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: displayHeader

   Displays the program header along with information about
   the program.
   ********************************************************** */

void displayHeader()
{
   cout << "\t\tSTR Data Center: Annual Rainfall Statistics\n\n"
        << "\t\tEnter the precipitation data for the past 12 months\n"
        << "\t\tto get information about the following:\n\n"
        << "\t\t   * The month with the highest amount of rainfall\n"
        << "\t\t   * The month with the lowest amount of rainfall\n"
        << "\t\t   * The average amount of rainfall of months total\n"
        << "\t\t   * The total annual amount of rainfall.\n"
        << "\t\t   * Precipitation data displayed and sorted in order\n"
        << "\t\t     from highest to lowest amount of rainfall.\n\n";
}

/* **********************************************************
   Definition: getRainfallData

   This function accepts rainfall, monthNames and NUM_MONTHS,
   containing the size of elements stored in the arrays, as
   its argument.

   It gets and stores the amount of precipitation for each
   month in a 12 month period and stores this information in
   rainfall.
   ********************************************************** */

void getRainfallData(double rainfall[], const string monthNames[],
                     int NUM_MONTHS)
{
   cout << "\n\t\tEnter the amount of rainfall for each month:\n\n";

   for (int index = 0; index < NUM_MONTHS; index++)
   {
      cout << "\t\tData for "
           << setw(9) << left << monthNames[index]
           << setw(5) << right << ": ";
      cin >> rainfall[index];

      /* Verify input */
      while (rainfall[index] < 0.0)
      {
         cout << "\n\t\tInput failure!\n"
              << "\n\t\tData for "
              << setw(9) << left << monthNames[index]
              << setw(5) << right << ": ";
         cin >> rainfall[index];
      }
   }
}

/* **********************************************************
   Definition: getTotalAmount

   This function accepts rainfall and NUM_MONTHS containing
   the size of the elements in the array as its arguments. It
   calculates and returns the total amount of rainfall over a
   12 month period.
   ********************************************************** */

double getTotalAmount(const double rainfall[], int NUM_MONTHS)
{
   double totalAmount = 0.0;

   for (int index = 0; index < NUM_MONTHS; index++)
   {
      totalAmount += rainfall[index];
   }

   return totalAmount;
}

/* **********************************************************
   Definition: getHighestAmount

   This function accepts rainfall and monthName arrays as its
   argument. It determines the month with the highest amount
   of rainfall and returns this value.
   ********************************************************** */

double getHighestAmount(const double rainfall[], const string monthNames[],
                        string &monthHighest, int NUM_MONTHS)
{
   double highestAmount = rainfall[0];

   /* Determine the highest amount of rainfall */
   for (int index = 0; index < NUM_MONTHS; index++)
   {
      if (rainfall[index] > highestAmount)
      {
         highestAmount = rainfall[index];
         monthHighest = monthNames[index];
      }
   }

   return highestAmount;
}

/* **********************************************************
   Definition: getLowestAmount

   This function accepts rainfall and monthName arrays as its
   argument. It determines the month with the lowest amount
   of rainfall and returns this value.
   ********************************************************** */

double getLowestAmount(const double rainfall[], const string monthNames[],
                       string &monthLowest, int NUM_MONTHS)
{
   double lowestAmount = rainfall[0];

   /* Determine the highest amount of rainfall */
   for (int index = 0; index < NUM_MONTHS; index++)
   {
      if (rainfall[index] < lowestAmount)
      {
         lowestAmount = rainfall[index];
         monthLowest = monthNames[index];
      }
   }

   return lowestAmount;
}

/* **********************************************************
   Definition: getAverageAmount

   This function accepts rainfall and NUM_MONTHS containing
   the number of elements of the array as its argument. It
   calculates the average amount of rainfall and returns the
   value.
   ********************************************************** */

double getAverageAmount(const double rainfall[], int NUM_MONTHS)
{
   /* Variable: Monthly average rainfall (accumulator) */
   double monthlyAverage = 0.0;

   /* Calculate: The average monthly amount of rainfall */
   for (int index = 0; index < NUM_MONTHS; index++)
   {
      monthlyAverage += rainfall[index] / NUM_MONTHS;
   }

   return monthlyAverage;
}

/* **********************************************************
   Definition: displayRainfallData

   This function displays the following items:

      * Month and month name with highest amount of rainfall
      * Month and month name with lowest amount of rainfall
      * Average amount of rainfall over a 12 month period
      * Total amount of rainfall over a 12 month period
   ********************************************************** */

void displayRainfallData(const double rainfall[], const double totalAmount,
                         const double highestAmount, const string monthHighest,
                         const double lowestAmount, const string monthLowest,
                         const double monthlyAverage, int NUM_MONTHS)
{
      /* Set up: Numeric output formatting */
   cout << fixed << showpoint << setprecision(2);

   cout << "\n\n\t\tSTR Data Center - Rainfall Statistic Data 2016\n\n"
        << "\t\tThe month with the highest rainfall was "
        << monthHighest << ".\n"
        << "\t\tThe amount of rainfall was: "
        << highestAmount << " inches.\n\n"
        << "\t\tThe Month with lowest rainfall was "
        << monthLowest << ".\n"
        << "\t\tThe amount of rainfall was: "
        << lowestAmount << " inches.\n\n"
        << "\t\tThe monthly average rainfall was "
        << monthlyAverage << " inches.\n\n"
        << "\t\tThe yearly total rainfall was "
        << totalAmount << " inches.\n\n";
}

/* **********************************************************
   Definition: sortRainfallData

   This function accepts rainfall and monthNames as arguments
   on which it performs an descending selection sort.
   ********************************************************** */

void sortRainfallData(double rainfall[], string monthNames[],
                      int NUM_MONTHS)
{
   int startScan = 0,
       maxIndex = 0,
       index = 0;

   string tempMonths = " ";
   double maxValue = 0.0;

   for (startScan = 0; startScan < (NUM_MONTHS - 1); startScan++)
   {
      maxIndex = startScan;
      maxValue = rainfall[startScan];
      tempMonths = monthNames[startScan];

      for (index = startScan + 1; index < NUM_MONTHS; index++)
      {
         if (rainfall[index] > maxValue)
         {
            maxValue = rainfall[index];
            tempMonths = monthNames[index];
            maxIndex = index;
         }
      }

      rainfall[maxIndex] = rainfall[startScan];
      monthNames[maxIndex] = monthNames[startScan];
      rainfall[startScan] = maxValue;
      monthNames[startScan] = tempMonths;
   }
}

/* **********************************************************
   Definition: displaySorted

   This function accepts rainfall and monthNames arrays as
   arguments. The function displays a header and the sorted
   list of rainfall data and month names in descending order.
   ********************************************************** */

void displaySorted(const double rainfall[], const string monthNames[],
                   int NUM_MONTHS)
{
   cout << "\n\t\tStatistics In Descending Order\n"
        << "\t\t(Highest -> Lowest Amount Of Rainfall)\n\n"
        << "\t\tMonth name\tAmount Rainfall\n";

   cout << fixed << showpoint << setprecision(2);

   for (int index = 0; index < NUM_MONTHS; index++)
   {
      cout << "\n\t\t" << setw(9) << left << monthNames[index] << ": "
                       << setw(19) << right << rainfall[index] << setw(5) << right;
   }

   cout << "\n";
}

Example Output: