// CIS 235 Exercise 1 // See page 413 for the code for a sort function #include #include using namespace::std; // // Function declarations a.k.a. function prototypes // // function will display on cout the contents of an arrary - FUNCTION 1 void printArray( ostream & out, const string data[], int cellsUsed); // function will sort an array - FUNCTION 2 void sortArray( string data[], int cellsUsed); int index_of_smallest(const string data[], int start_index, int cellsUsed); void swap_values(string& v1, string& v2); void main() { const int CELLS = 5; string names[CELLS] = { "tom", "mary", "ann", "bill","carol"}; cout << "Original array" << endl; printArray(cout,names,CELLS); cout << endl; sortArray(names,CELLS); cout << "Sorted array" << endl; printArray(cout,names,CELLS); cout << endl; } // end main // // Function definitions // // write FUNCTION 1 void printArray( ostream & out, const string data[], int cellsUsed) { for (int i = 0; i < cellsUsed; i++) { out << data[i] << " "; } } // write FUNCTION 2 void sortArray( string data[], int cellsUsed) { int index_of_next_smallest; for (int index = 0; index < cellsUsed - 1; index++) { // Place the correct value in data[index]: index_of_next_smallest = index_of_smallest(data, index, cellsUsed); swap_values(data[index], data[index_of_next_smallest]); // data[0] < = data[1] ... data[index] are the smallest of the original array // elements. The rest of the elements are in the remaining positions. } } int index_of_smallest(const string data[], int start_index, int cellsUsed) { string min = data[start_index]; int index_of_min = start_index; for (int index = start_index + 1; index < cellsUsed; index++) { if (data[index] < min) { min = data[index]; index_of_min = index; // min is the smallest of data[start_index] through data[index] } } return index_of_min; } void swap_values(string& v1, string& v2) { string temp; temp = v1; v1 = v2; v2 = temp; } /* Original array tom mary ann bill carol Sorted array ann bill carol mary tom Press any key to continue . . . */