Mike
Mike

Reputation:

Largest values on array

does anybody know how could I get the TWO most largest values from the third column on the following array?

$ar = array(array(1, 1,   7.50,   'Hello'),
              array(1, 2,  18.90,   'Hello'),
              array(3, 5,  11.50,   'Hello'),
              array(2, 4,  15.90,  'Hello'));

Output should be:

15.90
18.90

Thanks in advance

Upvotes: 1

Views: 1758

Answers (5)

Konrad Rudolph
Konrad Rudolph

Reputation: 546213

If you're sure that the value (two) will never change, just iterate over the array and keep track of the two largest numbers. If not, sort the arrays using usort() and providing an appropriate callback. Then take the first two values:

function cmp($a, $b) {
    $a = $a[2];
    $b = $b[2];
    return $a == $b ? 0 : $a < $b ? 1 : -1;
}

usort($ar, 'cmp');

Upvotes: 3

Hugh Bothwell
Hugh Bothwell

Reputation: 56714

Where are you getting the array data from? How often will the data change? Can you get the array already sorted by that field? If there are a large number of data items, might it be worth doing a second query?

Upvotes: 0

Claudiu
Claudiu

Reputation: 229601

A more general solution, for the n greatest values (pseudo-code)

def maxN(list, n):
    result = []
    curmin = 0
    for number in list:
        if number > curmin:
            binary insert number into result.    #O(log n)
            if len(result) > n:  
                truncate last element            #O(1)
            curmin = new minimum in result list  #O(1) since list is sorted

    return result

The whole thing will take... O(m log n), where m is the size of the list and n is the number of max elements you want. This is much better than if you sort the list, which takes O(n log n), for large n.

But it's also overkill if you just want the max two elements.

Upvotes: 3

Federico A. Ramponi
Federico A. Ramponi

Reputation: 47105

Sorting is O(n log n), but you can actually accomplish this in O(n) (that is, faster, if the array is big). Pseudocode follows:

first  = array[0][2]
second = array[1][2]
if second > first
   first, second = second, first
for tuple in array[2:n]
   if tuple[2] > second
      second = tuple[2]
   if second > first
      first, second = second, first

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 994937

One of the simplest ways to do this is to collect all the values into a single array, sort the array, then print out the first two values.

There are more efficient ways that don't involve sorting the whole array, but the above should get you started.

Upvotes: 0

Related Questions