Displaying highest 5 value from an array.

Hi all,

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.

1
2
3
4
5
6
7
8
9
10
11
12
float value[10] = {1.5, 1.2, 2.3, 1.3, 3.0, 2.2, 1.1, 2.0, 1.5, 1.0};
float highest = 0;

for(int i=0; i <= 9; i++)
{
   float number = value[i];
   
   if(highest < number)
   {
      highest = number;
   }
}


Any kind soul could help me?
It would become incredibly easy if you sorted the array first.
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'

EDIT: Err.. forgot about sorting :P
Last edited on
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;
		}
	}
}
Last edited on
thank you guys!

It will definitely be simpler if i sorted the array or creating a duplicated temporary array that will remove an element if it is picked.

However, my problem is that these values have their corresponding data. E.g.

1
2
float value[10] = {1.5, 1.2, 2.3, 1.3, 3.0, 2.2, 1.1, 2.0, 1.5, 1.0};
string name[10] = {atom, bravo, delta, foxy, romeo, zulu, quebac, charlie, echo, golf}
You can do linked-sorting (not an actual term):
1
2
3
4
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.
Last edited on
Topic archived. No new replies allowed.