Как найти максимальное значение массив

Another answer in this long list, but I think it’s worth it, because it provides some benefits that most (or all?) other answers don’t:

  1. The method below loops only once through the collection, therefore the order is O(N).
  2. The method finds ALL indices of the maximum values.
  3. The method can be used to find the indices of any comparison: min, max, equals, not equals, etc.
  4. The method can look into objects via a LINQ selector.

Method:

///-------------------------------------------------------------------
/// <summary>
/// Get the indices of all values that meet the condition that is defined by the comparer.
/// </summary>
/// <typeparam name="TSource">The type of the values in the source collection.</typeparam>
/// <typeparam name="TCompare">The type of the values that are compared.</typeparam>
/// <param name="i_collection">The collection of values that is analysed.</param>
/// <param name="i_selector">The selector to retrieve the compare-values from the source-values.</param>
/// <param name="i_comparer">The comparer that is used to compare the values of the collection.</param>
/// <returns>The indices of all values that meet the condition that is defined by the comparer.</returns>
/// Create <see cref="IComparer{T}"/> from comparison function:
///   Comparer{T}.Create ( comparison )
/// Comparison examples:
/// - max:      (a, b) => a.CompareTo (b)
/// - min:      (a, b) => -(a.CompareTo (b))
/// - == x:     (a, b) => a == 4 ? 0 : -1
/// - != x:     (a, b) => a != 4 ? 0 : -1
///-------------------------------------------------------------------
public static IEnumerable<int> GetIndices<TSource, TCompare> (this IEnumerable<TSource> i_collection,
                                                                   Func<TSource, TCompare> i_selector,
                                                                   IComparer<TCompare> i_comparer)
{
  if (i_collection == null)
    throw new ArgumentNullException (nameof (i_collection));
  if (!i_collection.Any ())
    return new int[0];

  int index = 0;
  var indices = new List<int> ();
  TCompare reference = i_selector (i_collection.First ());

  foreach (var value in i_collection)
  {
    var compare = i_selector (value);
    int result = i_comparer.Compare (compare, reference);
    if (result > 0)
    {
      reference = compare;
      indices.Clear ();
      indices.Add (index);
    }
    else if (result == 0)
      indices.Add (index);

    index++;
  }

  return indices;
}

If you don’t need the selector, then change the method to

public static IEnumerable<int> GetIndices<TCompare> (this IEnumerable<TCompare> i_collection,
                                                          IComparer<TCompare> i_comparer)

and remove all occurences of i_selector.

Proof of concept:

//########## test #1: int array ##########
int[] test = { 1, 5, 4, 9, 2, 7, 4, 6, 5, 9, 4 };

// get indices of maximum:
var indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a.CompareTo (b)));
// indices: { 3, 9 }

// get indices of all '4':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a == 4 ? 0 : -1));
// indices: { 2, 6, 10 }

// get indices of all except '4':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a != 4 ? 0 : -1));
// indices: { 0, 1, 3, 4, 5, 7, 8, 9 }

// get indices of all '15':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a == 15 ? 0 : -1));
// indices: { }

//########## test #2: named tuple array ##########
var datas = new (object anything, double score)[]
{
  (999,               0.1),
  (new object (),     0.42),
  ("hello",           0.3),
  (new Exception (),  0.16),
  ("abcde",           0.42)
};
// get indices of highest score:
indices = datas.GetIndices (data => data.score, Comparer<double>.Create ((a, b) => a.CompareTo (b)));
// indices: { 1, 4 }

Enjoy! :-)

Самый простой способ

Разумеется, проще всего получить минимальный и максимальный элементы массива с помощью функций min() и max():

$arr = [8, 4, 12, 9];
$max = max($arr); // 12
$min = min($arr); // 4

Однако на форумах часто просят написать скрипт, не использующий эти функции. Чаще всего этого требуют преподаватели учебных учреждений.

Условия задачи

1. Найти наибольший наименьший элементы в одномерном числовом массиве.
2. Определить номер минимального и максимального элементов заданного одномерного массива.
3. Найти минимальное и максимальное значение в ассоциативном массиве.

Общий принцип поиска элементов

Во всех решениях мы будем использовать одну и ту же логику.

Согласно условию, нам необходимо объявить числовой массив произвольной длины. Также объявим 4 переменные, в которые будем помещать найденные значения и их ключи:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

Далее перебираем массив в цикле и на каждой итерации проверяем, больше ли текущее значение, чем самое большое, что мы находили до этого.

И если больше — будем записывать в $max новое максимальное значение, а в $max_key его ключ. Абсолютно также поступим и с минимальными ключом и значением.

Пример с циклом foreach:

foreach($arr as $k => $v)
{
	if($v > $max)
	{
		$max = $v;
		$max_key = $k;
	}

	if($v < $min)
	{
		$min = $v;
		$min_key = $k;
	}
}

На данном этапе наш код уже будет работать, но это ещё не всё. Попробуем изменить исходный массив и посмотрим на результат:

<?php
$arr = [0, -12];
$max = null;

foreach($arr as $v)
{
	if($v > $max)
		$max = $v;
}

var_dump($max); // -12

Максимальным должно быть число 0, но скрипт вывел -12. Дело в том, что PHP не считает истинным выражение 0 > null, поэтому ноль на первой итерации цикла не записался в переменную $max.

Для решения этой проблемы просто добавим условие, что если $max === null, т.е. если это первая итерация, то в любом случае записываем текущее значение в $min и $max:

<?php
$arr = [0, -12];
$max = null;

foreach($arr as $v)
{
    if($v > $max or $max === null)
        $max = $v;
}

var_dump($max); // -12

Минимальный и максимальный элементы с циклом FOREACH

Решение:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

foreach($arr as $k => $v)
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = $k;
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = $k;
	}
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Минимальный и максимальный элементы с циклом WHILE

Решение 1: счётчик + count()

Цикл будет выполняться до тех пор, пока значение счётчика $i не превысит количество элементов массива.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while($i < count($arr))
{
    if($arr[$i] > $max or $max === null)
    {
        $max = $arr[$i];
        $max_key = $i;
    }

    if($arr[$i] < $min or $min === null)
    {
        $min = $arr[$i];
        $min_key = $i;
    }

	$i++;
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 2: счётчик + isset()

Запускаем вечный цикл while и в каждой итерации цикла проверяем существование следующего элемента с помощью isset(). Если его нет — выходим из цикла оператором break:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while(true)
{
	if(isset($arr[$i]))
	{
		if($arr[$i] > $max or $max === null)
		{
			$max = $arr[$i];
			$max_key = $i;
		}

		if($arr[$i] < $min or $min === null)
		{
			$min = $arr[$i];
			$min_key = $i;
		}
	}
	else
		break;

	$i++;
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 3: list() + each()

Функция each() возвращает ключ и значение текущего элемента массива и смещает его внутренний указатель на единицу. Функция list() используется просто для удобства — с её помощью мы превращаем массив, который возвращает функция each, в две разные переменные:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while(list($k, $v) = each($arr))
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = $k;
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = $k;
	}
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Получился практически аналог foreach. Единственный минус в том, что начиная с PHP 7.2 функция each() объявлена устаревшей.

Решение 4: current() + next()

Это решение похоже на предыдущее с each(). Получаем текущий элемента массива функцией current() и смещаем внутренний указатель массива функцией next(). Получить текущий ключ массива можно с помощью функции key().

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while($v = current($arr))
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = key($arr);
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = key($arr);
	}

	next($arr);
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Наибольший и наименьший элементы с циклом FOR

Решение 1: счётчик + count()

Вводим счётчик $i и увеличиваем его после каждой итерации. Цикл прекратится как только значение счётчика превысит количество элементов массива.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

for($i = 0; $i < count($arr); $i++)
{
    if($arr[$i] > $max or $max === null)
    {
        $max = $arr[$i];
        $max_key = $i;
    }

    if($arr[$i] < $min or $min === null)
    {
        $min = $arr[$i];
        $min_key = $i;
    }
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 2: счётчик + isset()

В отличие от предыдущего варианта, мы не смотрим на количество элементов массива, а запускаем вечный цикл и в каждой итерации проверяем существование следующего элемента, и если его нет — прерываем цикл командой break:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

for($i = 0; true; $i++)
{
	if(!isset($arr[$i]))
		break;

    if($arr[$i] > $max or $max === null)
    {
        $max = $arr[$i];
        $max_key = $i;
    }

    if($arr[$i] < $min or $min === null)
    {
        $min = $arr[$i];
        $min_key = $i;
    }
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 3: each() + list()

Функция each() возвращает массив с ключом и значением текущего элемента массива, а list() превращает этот массив в 2 разные переменные. После последнего элемента функция each() вернёт false и цикл прекратит работу.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

for(; list($k, $v) = each($arr);)
{
    if($v > $max or $max === null)
    {
        $max = $v;
        $max_key = $k;
    }

    if($v < $min or $min === null)
    {
        $min = $v;
        $min_key = $k;
    }
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 4: current() + next()

С помощью функции next() смещаем внутренний указатель массива, а функции current() и key() возвращают текущие ключ и значение. Первое и последнее выражение цикла оставляем пустыми.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

for(; $v = current($arr);)
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = key($arr);
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = key($arr);
	}

	next($arr);
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Максимальное значение в ассоциативном массиве

В ассоциативных массивах отсутствует порядок или системность в названиях ключей, поэтому циклы со счётчиками здесь недоступны.

Но мы всё ещё можем использовать цикл foreach и те решения для while и for, где используются функции each() и next(), поскольку они используют не ключи, а внутренний указатель массива.

If you are looking for the quickest and simplest way to perform various actions in regards to arrays, the use of the Collections class is extremely helpful (documentation available from https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html), actions ranges from finding the maximum, minimum, sorting, reverse order, etc.

A simple way to find the maximum value from the array with the use of Collections:

Double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4, 8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2, 3.5, 3.0, 1.1, 6.5, 5.1, -1.2, -5.1, 2.0, 5.2, 2.1};
List<Double> a = new ArrayList<Double>(Arrays.asList(decMax));
System.out.println("The highest maximum for the December is: " + Collections.max(a));

If you are interested in finding the minimum value, similar to finding maximum:

System.out.println(Collections.min(a));

The simplest line to sort the list:

Collections.sort(a);

Or alternatively the use of the Arrays class to sort an array:

Arrays.sort(decMax);

However the Arrays class does not have a method that refers to the maximum value directly, sorting it and referring to the last index is the maximum value, however keep in mind sorting by the above 2 methods has a complexity of O(n log n).

(PHP 4, PHP 5, PHP 7, PHP 8)

maxВозвращает наибольшее значение

Описание

Альтернативная сигнатура (не поддерживается с именованными аргументами):

max(array $value_array): mixed

Замечание:

Значения разных типов будут сравниваться в соответствии со стандартными правилами сравнения.
К примеру, нечисловая строка (string) будет сравниваться с целым числом
(int) так, как будто это 0, а множество
нечисловых строк (string) будут сравниваться алфавитно-цифровым
порядком. Выбранное значение будет возвращено без конвертации типа.

Предостережение

Будьте осторожны при передаче аргументов разных типов, поскольку результат
max() может вас удивить.

Список параметров

value

Любое поддающееся сравнению
значение.

values

Любые поддающиеся сравнению
значения.

value_array

Массив, содержащий значения.

Возвращаемые значения

max() вернёт значение «наибольшего» из элементов массива, в
соответствии со стандартными правилами сравнения. Если несколько разнотипных
значений посчитаются идентичными (например 0 и
'abc'), функция вернёт первое из них.

Ошибки

Если передан пустой массив, функция max()
выбрасывает ошибку ValueError.

Список изменений

Версия Описание
8.0.0 Функция max() теперь в случае возникновения ошибки
выбрасывает ошибку ValueError;
ранее возвращалось значение false и выдавалась ошибка уровня E_WARNING.

Примеры

Пример #1 Пример использования max()


<?php
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5

// 'hello' будет представлено как числовое значение 0.
// Оба параметра имеют одинаковое значение, поэтому результат
// определяется порядком, в котором параметры переданы

echo max(0, 'hello'); // 0
echo max('hello', 0); // hello

// Здесь сравниваются -1 < 0, так что 'hello' больше

echo max('hello', -1); // hello

// В данном случае 0 больше, чем -1, поэтому результат равен 'hello'.

echo max(-1, 'hello'); // hello

// При сравнении массивов, разной длины - max вернёт более длинный

$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)

// При сравнении массивов одинаковой длины - max будет сравнивать их поэлементно
// слева направо, в данном примере 2 == 2, но 4 < 5

$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)

// Если передан массив и не массив, в результате всегда будет возвращён массив

$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)

// Если один из аргументов NULL или булево значение, то сравнение с другими
// значениями будет происходить по правилу FALSE < TRUE, вне зависимости от того
// какого типа параметры переданы.
// В примере ниже, -10 трактуется как TRUE

$val = max(-10, FALSE); // -10

// 0 всегда трактуется как FALSE, значит он "меньше чем" TRUE

$val = max(0, TRUE); // TRUE
?>

Смотрите также

  • min() — Находит наименьшее значение
  • count() — Подсчитывает количество элементов массива или Countable объекте

keith at bifugi dot com

6 years ago


The simplest way to get around the fact that max() won't give the key is array_search:

<?php
$student_grades
= array ("john" => 100, "sarah" => 90, "anne" => 100);
$top_student = array_search(max($student_grades),$student_grades); // john
?>

This could also be done with array_flip, though overwriting will mean that it gets the last max value rather than the first:

<?php
$grades_index
= array_flip($student_grades);
$top_student = $grades_index[max($student_grades)]; // anne
?>

To get all the max value keys:

<?php
$top_students
= array_keys($student_grades,max($student_grades)); // john, anne
?>


deoomen

11 months ago


Watch out after PHP 8.0!

Sample code:

<?php
echo max(0,'hello');
?>

Before PHP 8.0 will return int(0) but since PHP 8.0 above code returns string("hello")!!


volch5 at gmail dot com

9 years ago


max() (and min()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php
$dt1
= new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo
max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17

marcini

14 years ago


Note that max() can compare dates, so if you write something like this:

<?php
$dates
= array('2009-02-15', '2009-03-15');
echo
max($dates);
?>

you will get: 2009-03-15.


costinu

11 years ago


max(null, 0) = null

max(0, null) = 0

Alex Rath

13 years ago


Notice that whenever there is a Number in front of the String, it will be used for Comparison.

<?php

  max

('7iuwmssuxue', 1); //returns 7iuwmssuxu
 
max('-7suidha', -4); //returns -4?>

But just if it is in front of the String

<?php

  max

('sdihatewin7wduiw', 3); //returns 3?>


ReVo_

8 years ago


Sometimes you could need to get the max from an array which looks like this:

<?php
$arrTest
= array(
    array(
"day" => 1, "b" => 10 ),
    array(
"day" => 2, "b" => 43 ),
    array(
"day" => 3, "b" => 2 ),
    array(
"day" => 4, "b" => -3 ),
    array(
"day" => 5, "b" => 4 ),
    array(
"day" => 6, "b" => -5 )
);
?>
all max functions i see around don't provide a way to get the max value of the values in (example) key "b"

<?php
function maxValueInArray($array, $keyToSearch)
{
   
$currentMax = NULL;
    foreach(
$array as $arr)
    {
        foreach(
$arr as $key => $value)
        {
            if (
$key == $keyToSearch && ($value >= $currentMax))
            {
               
$currentMax = $value;
            }
        }
    }

    return

$currentMax;
}
//                                            array       key
$value = maxValueInArray($arrTest, "b");?>

output: 43


ries at vantwisk dot nl

14 years ago


I had several occasions that using max is a lot slower then using a if/then/else construct. Be sure to check this in your routines!

Ries


johnphayes at gmail dot com

17 years ago


Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true


michaelangel0 at mail.com

15 years ago


Matlab users and others may feel lonely without the double argument output from min and max functions.

To have the INDEX of the highest value in an array, as well as the value itself, use the following, or a derivative:

<?php

function doublemax($mylist){

 
$maxvalue=max($mylist);

  while(list(
$key,$value)=each($mylist)){

    if(
$value==$maxvalue)$maxindex=$key;

  }

  return array(
"m"=>$maxvalue,"i"=>$maxindex);

}

?>


php at rijkvanwel dot nl

12 years ago


To get the largest key in an array:

<?php
$array
= array( 0 => 'first', 1=> 'second', /* ... */ 99 => 'nth' );
$max_key = max( array_keys( $array ) ); // 99
?>


info at osworx dot net

4 years ago


Be aware if a array like this is used (e.g. values from a shopping cart):
<?php
Array
(
    [
0] => 142,80
   
[1] => 39,27
   
[2] => 22,80
   
[3] => 175,80
)?>
The result will be: 39,27 and not - as expected - 175,80

So, to find the max value, use integer only like:
<?php
Array
(
    [
0] => 14280
   
[1] => 3927
   
[2] => 2280
   
[3] => 17580
)?>
and you will get the correct result: 17580


sun at drupal dot org

11 years ago


Note that max() throws a warning if the array is empty:

<?php
$a
= array();
max($a);
// Warning: max(): Array must contain at least one element
?>

So make sure your data isn't empty.


harmor

15 years ago


A way to bound a integer between two values is:

<?php

function bound($x, $min, $max)

{

     return
min(max($x, $min), $max);

}

?>



which is the same as:

<?php

$tmp
= $x;

if(
$tmp < $min)

{

   
$tmp = $min;

}

if(
$tmp > $max)

{

    
$tmp = $max;

}

$y = $tmp;

?>



So if you wanted to bound an integer between 1 and 12 for example:

Input:

<?php

$x
= 0;

echo
bound(0, 1, 12).'<br />';

$x = 1;

echo
bound($x, 1, 12).'<br />';

$x = 6;

echo
bound($x, 1, 12).'<br />';

$x = 12;

echo
bound($x, 1, 12).'<br />';

$x = 13;

echo
bound($x, 1, 12).'<br />';

?>



Output:

1

1

6

12

12


levim at php dot net

10 years ago


<?php
/**
* @param array $array
*
* @return int|null Returns the largest value of the array. Returns NULL if no
*     integers are found.
*/
function array_max_recursive(array $array) {
   
$max = NULL;
   
$stack = array($array);

    do {

$current = array_pop($stack );
        foreach (
$current as $value) {
            if (
is_array($value)) {
               
$stack[] = $value;
            } elseif (
filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
               
// max(NULL, 0) returns NULL, so cast it
               
$max = (int) max($max, $value);
            }
        }

    } while (!empty(

$stack));

    return

$max;
}
?>

- This function is not actually recursive, but fulfills the requirement that it works on sub-arrays.  I do this because PHP is not very good at recursion.  I also did it because I enjoy doing things this way. 
- It returns something of type int, never a string representation of an int. The exception is when you provide an array that does not contain any integers.  It will then return NULL.
- It ignores non-array, non-int values.

toon dot baeyens at gmail dot com

11 years ago


A little function for multi-dimensional arrays:
<?php
function amax($array){
    if(
is_array($array)){
        foreach(
$array as $key => $value){
           
$array[$key] = amax($value);
        }
        return
max($array);
    }else{
        return
$array;
    }
}
?>

blackmac01 at gmail dot com

3 years ago


In response to: keith at bifugi dot com

If you want to find the specific key(s) that match the maximum value in an array where the values may be duplicated, you can loop through and perform a simple check:
<?php# Example Array
$a = array(
    
'key1' => 100,
    
'key2' => 90,
    
'key3' => 100,
    
'key4' => 90,
);
# First get the maximum value
$max = max($a);# Create a new array containing all keys which have the max value
foreach($a as $key => $val) {    
     if(
$val === $max) $b[] = $key;
}
# If you want a string list, just do this
$b = implode(' ', $b);
?>

This produces consistent results and will scale well in terms of performance, whereas functions like array_search and array_flip can lead to degraded performance when dealing with large amounts of data.


chris at candm dt org dt uk

1 year ago


A function to return the key of the max value of an array. For multiple max values, it will return the key of first. Change > to >= to get the last.

function array_max_key($arr) {
    $maxkey='';
    $maxval=false;
    array_walk($arr,
        function (&$cval,&$ckey) use(&$maxkey,&$maxval) {
            if ($maxval === false || $cval > $maxval) {
                $maxval = $cval;
                $maxkey = $ckey;
            }
        }
    );
    return $maxkey;
}


Michael Blinn

4 years ago


Be careful using max() with objects, as it returns a reference not a new object.

<?php

$min_date

= date_create('2019-03-05');
$max_date = date_create('2019-03-06');$date_by_reference = max($min_date, $max_date);// $date_by_reference and $max_date are now the same objectecho '$max_date is ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-06'
echo '$date_by_reference is ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-06'date_add($date_by_reference, date_interval_create_from_date_string('1 days')); // Add 1 day to $date_by_reference, changes $max_date tooecho '$max_date is changed ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-07'
echo '$date_by_reference is changed ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-07'?>


В этом посте мы обсудим, как найти минимальный и максимальный элемент массива в C++.

1. Наивное решение

Наивное решение — написать собственную процедуру для этой простой задачи. Идея состоит в том, чтобы линейно пройти массив, используя простой цикл for или цикл for на основе диапазона. Затем для каждого обнаруженного элемента мы сравниваем его с минимальным или максимальным элементом, найденным до сих пор, и заменяем максимальный элемент, найденный до сих пор, текущим элементом, если он меньше по значению, и минимальный элемент, найденный до сих пор, текущим элементом, если он больше по стоимости.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

#include <iostream>

#include <climits>

#include <algorithm>

using namespace std;

int main()

{

    int arr[] = { 4, 2, 1, 6, 8, 5 };

    int min = INT_MAX, max = INT_MIN;

    for (int i: arr)

    {

        if (i < min) {

            min = i;

        }

        if (i > max) {

            max = i;

        }

    }

    std::cout << «The min element is « << min << std::endl;

    std::cout << «The max element is « << max << std::endl;

    return 0;

}

Скачать  Выполнить код

результат:

The min element is -8
The max element is 6

2. Использование minmax_element() функция

Рекомендуемое решение — использовать std::minmax_element найти наименьший и наибольший элементы массива. Он возвращает пару итераторов, первое значение которых указывает на минимальный элемент, а второе значение указывает на максимальный элемент. Он определен в <algorithm> заголовок.

#include <iostream>

#include <algorithm>

using namespace std;

int main()

{

    int arr[] = { 4, 2, 1, 6, 8, 5 };

    std::pair<int*, int*> minmax = std::minmax_element(std::begin(arr), std::end(arr));

    std::cout << «The min element is « << *(minmax.first) << std::endl;

    std::cout << «The max element is « << *(minmax.second) << std::endl;

    return 0;

}

Скачать  Выполнить код

результат:

The min element is -8
The max element is 6

3. Использование min_element() с max_element() функция

Стандартная библиотека C++ также предоставляет отдельные функции. min_element() а также max_element() чтобы найти наименьший и наибольший элементы в массиве соответственно.

#include <iostream>

#include <algorithm>

using namespace std;

int main()

{

    int arr[] = { 4, 2, 1, 6, 8, 5 };

    int *min = std::min_element(std::begin(arr), std::end(arr));

    int *max = std::max_element(std::begin(arr), std::end(arr));

    std::cout << «The min element is « << *min << std::endl;

    std::cout << «The max element is « << *max << std::endl;

    return 0;

}

Скачать  Выполнить код

результат:

The min element is -8
The max element is 6

Вот и все, что касается нахождения минимального и максимального значений в массиве в C++.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти прикольную песню
  • Как найти предельный угол полного внутреннего отражения
  • Как найти снимать в порно
  • Как найти русские сервера в виар чате
  • Как найти объем товара в экономике

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии