1

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

Slartibartfast
8,8056 gold badges44 silver badges45 bronze badges
asked Oct 31, 2008 at 20:47

5 Answers 5

3

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');
NullUserException
85.7k31 gold badges212 silver badges239 bronze badges
answered Oct 31, 2008 at 20:52
3

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
answered Oct 31, 2008 at 21:00
1
  • Curious how we can write Python code, omit some colon, and call it pseudocode. Isn't it?:^) Commented Nov 1, 2008 at 3:25
3

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.

answered Oct 31, 2008 at 21:16
0

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.

answered Oct 31, 2008 at 20:53
0

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?

answered Nov 1, 2008 at 1:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.