tags:

views:

395

answers:

4

I made an array in PHP which holds a bucnh of unix timestamps.

I'm trying to make a function that will return an array containing the indexes of the 3 largest numbers in that array.

For instance, if the largest numbers are located at indexes 3,5 and 8

And if the largest is 5, second largest is 8 and smallest of the three is number 3, I want an array that holds the values (5,8,3) in that order.

And frankly, I don't have a clue how to pull this off. Does anybody know how to do this?

+1  A: 

Simon posted the simple and probably good-enough performing method.

The other option, only if you have a really large array, is to scan through the array and keep track of the indexes of the three highest values you see. This is O(n), but (especially since its in interpreted PHP code, not a compiled built-in function), probably slower for all but the largest of arrays.

derobert
+7  A: 

You could use asort to sort the array and maintain index and then use slice along with the 4th parameter, again to maintain the index, to grap the top x number of elements you are after, and finally use array_keys.

There may well be a quicker way, but it's just to show there are plenty of PHP array functions to help you achieve the effect you're looking for.

Simon
Thanks, this solved my problem with one little exception. The function that gave me the 3 largest values as the first 3 numbers in the new array needs to be arsort, instead of asort
Vordreller
Ah, glad it helped. Alternatively you could have used array_slice to slice the other end of the array - but it's the same difference really.
Simon
A: 

In pseudo-code:

function select(list[1..n], k)
     for i from 1 to k
         maxIndex = i
         maxValue = list[i]
         for j from i+1 to n
             if list[j] > maxValue
                 maxIndex = j
                 maxValue = list[j]
         swap list[i] and list[maxIndex]
     return list[k]

newarray[] = select(array, 1);
newarray[] = select(array, 2);
newarray[] = select(array, 3);
mepcotterell
A: 

In PHP code:

function threeLargest($array){
 krsort($array, "SORT_NUMERIC");
 $return[0] = $array[0];
 $return[1] = $array[1];
 $return[2] = $array[2];
 return $return;
}
Pim Jager
this did not work. For some reason, non of the sorting functions for arrays seem to be working in my debugger...
Vordreller