• 0

[Logic] Find top five from n


Question

Hi, I'm having trouble with how to get the logic right to find the top five of a given set of numbers.

So say I've got {5,4,7,3,21,232,53,235,211,74} how can I find out which are the maximum five numbers, i.e. {235,232,211,74,53}?

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

http://en.wikipedia.org/wiki/Sorting_algorithm

This should work too, translate it to whatever language you want.

var numArray:Array;			//Array of numbers
var maxNumArray:Array;		//Array of max numbers returned

var numMaxNum:int;			//The number of times you want it to run (setting this to numArray.length will sort the whole array)
var tempMax:int;			//Temp maxNum holder
var tempIndex:int;			//Holds temp maxNum index

for (var i:int = 0; i < numMaxNum; i++)
{
	tempMax = 0;
	tempIndex = 0;

	for (var j:int = 0; j < numArray.length; j++)
	{
		if(numArray[j] > tempMax)
		{
			tempMax = numArray[j];
			tempIndex = j;
		}
	}

	numArray.splice(tempIndex,1);
	maxNumArray.push(tempMax);
}

trace(maxNumArray);

Edited by mail
Link to comment
Share on other sites

  • 0

The EASY (not necessarily the best) way to do it is to sort your array.

The other way to do it is having a buffer of size 5 with a variable for the lowest number in said array. You'd sort this array and iterate through the array of numbers and substitute the lowest number whenever you find one that is higher. (I believe this is O(n))

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.