#include #include #include // Function declarations double maximum_unreturned( double const array[], bool has_been_returned[], std::size_t const capacity ); int main(); // Function definitions int main() { double data[10]{ 5.34, -4.15, 4.65, -4.59, -8.69, 4.42, 8.40, 1.80, -4.50, 2.65 }; bool visited[10]{}; // All entries are false. // This should print the entries from largest // to smallest, followed by -infinity twice. // // The final two calls occur after all entries // of visited have been set to true. for ( std::size_t k{ 0 }; k < 12; ++k ) { std::cout << maximum_unreturned( data, visited, 10 ) << std::endl; } return 0; } /*************************************************** * maximum_unreturned * * Find the maximum entry in array for which the * corresponding entry in has_been_returned is * false. * * Before returning that value, set the * corresponding entry in has_been_returned to * true. * * Assume that every entry of array is finite. * * If several entries equal the maximum, any one * of them may be selected. * * If there are no unreturned entries, return * negative infinity. ***************************************************/ double maximum_unreturned( double const array[], bool has_been_returned[], std::size_t const capacity ) { return -std::numeric_limits::infinity(); } // Hint: // // Begin by assuming that the maximum value is // negative infinity. // // You must also remember the index at which the // maximum was found. Initially, no index has been // found, so you can use capacity to indicate this: // // std::size_t max_index{ capacity }; // // Go through the array and consider an entry only // if // // has_been_returned[k] // // is false. // // If such an entry is greater than the maximum // found so far, remember both its value and its // index. // // Once you have finished searching, if max_index // is not equal to capacity, set // // has_been_returned[max_index] // // to true before returning the maximum value. // // If no such entry was found, max_index will still // equal capacity and the maximum value will still // be negative infinity. // One solution: /* double maximum_unreturned( double const array[], bool has_been_returned[], std::size_t const capacity ) { double max_value{ -std::numeric_limits::infinity() }; std::size_t max_index{ capacity }; for ( std::size_t k{ 0 }; k < capacity; ++k ) { if ( !has_been_returned[k] && array[k] > max_value ) { max_value = array[k]; max_index = k; } } if ( max_index != capacity ) { has_been_returned[max_index] = true; } return max_value; } */