With this code I am working on manipulating numbers in an array and passing them through functions.
I am using a bubble sort to pick out the highest and lowest numbers in the array. I then want to output the original order that I typed the numbers into the array before they were sorted from highest to lowest and lowest to highest. How do I achieve this? I tried passing just one variable in the array but this resulted in my program simply outputting "0" for highest and lowest number.
If you don't understand my question I will be happy to clarify.
I am also aware my averages aren't working. That will be fixed later.
Bubblesort is way overkill to find the highest and/or lowest values in an array.
Bubblesort runs in O(n^2) time whereas finding the highest and/or lowest value should run in linear time.
One way to accomplish what you want is to use the standard algorithms:
1 2 3 4 5
#include <algorithm>
template< typename T, size_t N >
T highestGrade( T (&array)[ N ] )
{ return *std::max_element( array, array + N ); }
Or if you're unfamiliar with templates
1 2
int highestGrade( int array[], size_t numElems )
{ return *std::max_element( array, array + numElems ); }
And if you need to write the loop yourself, then here's one way to do it:
1 2 3 4 5 6 7 8 9
int highestGrade( int array[], size_t numElems )
{
int highest = array[ 0 ]; // Assumes numElems > 0
for( size_t i = 1; i < numElems; ++i )
if( array[ i ] > highest )
highest = array[ i ];
return highest;
}
Note that all of the above functions avoid the problem of having your grade list
change as a result of the bubblesort.
Still another alternative is to make a copy of the array and pass the copy to highestGrade() and lowestGrade():
1 2 3 4 5 6 7 8 9 10 11
int main() {
int grades[ 5 ];
int gradeCopy[ 5 ];
size_t elements = 5;
getGrades( grades, elements );
memcpy( gradeCopy, grades, sizeof( grades ) );
// Or std::copy( grades, grades + 5, gradeCopy );
// ...
}