ro ko
ro ko

Reputation: 2986

Find the max value in an array

My requirement is to find the greatest/max value in an array, which may contain other arrays within it. For example we could have a look at an array below.

$array =
    array(
        13,
        array(10, 4, 111, 3),
        4,
        array(23, 450, 12,array(110, 119, 20, 670), 45 ,45,67,89),
        );

$max = find_max($array, 0);

print "Maximumum Value is  $max";

I already have a working function find_max, but all I wanted to know is what could the best and efficient possible way to do this other than the code given below.

function find_max($array, $maxValue) {
    foreach ($array as $member) {
        if (is_array($member)) {
            $maxValue = find_max($member, $maxValue);
        } else {

            if($member==$maxValue){
                continue;
            }
            if ($member > $maxValue) {
                $maxValue = $member;
            }
        }
    }
    return $maxValue;
}

Upvotes: 4

Views: 2085

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53525

Finding the max value requires O(n), so you can't improve it drastically, as far as I know. But, you can add a minor improvement to your code:

function find_max($array, $maxValue) {
    foreach ($array as $member) {
        if (is_array($member)) {
            $maxValue = find_max($member, $maxValue);
        } else {
            if ($member > $maxValue) {
                $maxValue = $member;
            }
        }
    }
    return $maxValue;
}

$array =
array(
    13,
    array(10, 4, 111, 3),
    4,
    array(23, 450, 12,array(110, 119, 20, 670), 45 ,45,67,89),
    );
$ans = find_max($array, 0);
echo "ans = $ans";

output: 670

Upvotes: 1

Jared Drake
Jared Drake

Reputation: 1002

Really, what you're doing would be the best way to search for a max in a multidimensional array. Utilizing recursion to find the depth and checking for the greater number. Sorry, there just isn't a built in function to do this.

This is some complicated way to sort a multidimensional array based on the inner most array, but it's a fairly involved concept. (searches for it).

usort might be of use?

Upvotes: 1

Jeff
Jeff

Reputation: 820

You can't find the max of an array (or an array of arrays) faster than O(n) or linear time.

If you need to constantly find the max of this array, I would recommend sorting the array or using a different (sorted) data structure all together if possible.

You could also keep a reference to the max and update it when you insert data. Obviously this assumes you are inserting the data yourself and not getting it from somewhere else, in which case my last comment is useless to you.

Upvotes: 2

Related Questions