Moustacha Posted August 22, 2009 Share Posted August 22, 2009 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 More sharing options...
0 mail Posted August 22, 2009 Share Posted August 22, 2009 (edited) 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 August 22, 2009 by mail Link to comment Share on other sites More sharing options...
0 Argote Posted August 25, 2009 Share Posted August 25, 2009 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 More sharing options...
Question
Moustacha
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