I am tasked to display the highest 5 values from an array of 10 float variables. However my codes only able to let me get the highest value. I still couldnt get the top 5 results.
For most problems there is more than one solution... A solution that would work would be creating a temporary array that is a duplicate and removing an element if it has been 'picked'
What you can do is sort the array out in order.
then use another loop to display the first 5 items in that array
for sorting:
1 2 3 4 5 6 7 8 9 10 11 12
for (int i = 9; i >= 0; i--)
{
for (int x = 0; x < 10; x++)
{
if (value[x] > value[x+1])
{
int temp = value[x+1];
value[x+1] = value[x];
value[x] = temp;
}
}
}
if (value[i]>value[j]) {
doSwap(name[i],name[j]); // Make your own doSwap function
doSwap(value[i],value[j]);
}
Alternatively, you can keep a secondary array that keeps (the indexes of) the largest 5 values. A somewhat efficient way of doing this is by checking each value with the last (thus lowest) of the max5 values. If it is higher, overwrite the last (thus discarding the previous 5th highest, as it is no longer part of max5). Then, check if the new 5th is higher than the 4th. If so, swap locations (4th becomes 5th, new member becomes 4th). Then do the same for 3rd location and so on, until it is at its proper location (first, or until the next element is higher).
You can do the same with keeping the indexes instead of the actual values (thus allowing you directly look up your strings as well). You'll simply have to access value[] at each comparison. Initializing becomes more difficult though. In the value-driven way, you could initialize max5 with any value lower than the minimum (0, or -1 to be sure). For the index-driven approach, you'll have to initialize with the first 5 values of value[] and then sort it. Since max5 is half of value's size, you'd actually be better off with sorting the entire array. For larger sets, it can be worth the trouble.