如何在数组中找到最小值和最大值?

7

你好,我该如何在Delphi中找出最大值和最小值?

假设有10个不同的数字存储在一个数组中:

如何找到数组中的最大值和最小值?

3个回答

6

只需要按线性方式循环遍历数组。保持一个变量用于存储最小值,另一个变量用于存储最大值。将这两个变量都初始化为数组中的第一个值。然后,对于每个元素,如果该元素小于最小值或大于最大值,则更新最小值或最大值。

minval := a[0];
maxval := a[0];
for i := 1 to Count-1 do
begin
  if a[i]<minval then
    minval := a[i]
  else if a[i]>maxval then
    maxval := a[i];
end;

显然,此代码假定Count>0。

请注意,您也可以使用Math单元中的MinValue和MaxValue例程。


我觉得我们同时在打字!我喜欢你的初始化方式,但我更喜欢更紧凑的for..in结构,尽管这取决于他使用的Delphi版本是否支持。 - Richard A
3
+1 用于 MinValue 和 MaxValue。还有 MinIntValue 和 MaxIntValue。 - NGLN
@ngln 谢谢你的回复,当然你是对的,我习惯性地使用浮点数据。 - David Heffernan
但是我的数字是int64类型的。当我找到最小值时,出现了一个问题,即-112322654564545不是整数值。 - dnaz

4

遍历数组并与之前找到的最小值和最大值进行比较。

这里是一段代码片段。根据您的澄清,我已编辑代码以使用Int64。

Min := High(Int64);
Max := Low(Int64);
for ThisNumber in MyArray do
begin
  if ThisNumber < Min then
  begin
    Min := ThisNumber;
  end
  if ThisNumber > Max then
  begin
    Max := ThisNumber;
  end;
end;

有趣的是,在 Math.pas 文件中,MaxIntValue 的实现如下:

function MaxIntValue(const Data: array of Integer): Integer;
var
  I: Integer;
begin
  Result := Data[Low(Data)];
  for I := Low(Data) + 1 to High(Data) do
    if Result < Data[I] then
      Result := Data[I];
end;

该实现与David的答案类似,使用第一个数组值作为初始值。这假定数组至少有一个元素。还要注意,循环可以从Low(Data) + 1开始,并节省一次不必要的比较。对于您描述的数据,每个数组有100个元素,最多可获得1%的速度提高。
如果性能不重要,则MinIntValue和MaxIntValue会更简洁。如果自己编写代码,则只需要迭代一次而不是两次。

-1

Create a function that takes an array of numbers and return both the minimum and maximum numbers, in that order.

// Examples
// minMax([1, 2, 3, 4, 5]) ➞ [1, 5]

// minMax([2334454, 5]) ➞ [5, 2334454]

// minMax([1]) ➞ [1, 1]

const minMax = (arr) => {
  let newMinMax = [];
  let min = Math.min(...arr);

  newMinMax.push(min);
  let max = Math.max(...arr);

  newMinMax.push(max);
  return newMinMax;
};

// console.log(minMax([1, 2, 3, 4, 5]));
// console.log(minMax([2334454, 5]));
// console.log(minMax([1]));

Used javascript build in functions for that .Math.min function requires distinct number but when we provide array it will give you a NaN to avoid that use [...arr]
spread operator of Math.min.apply(Math,arr) function.


3
题目明确要求使用Delphi进行解决方案。而你的代码是JavaScript的,那么它如何帮助呢? - Adrian Mole
我刚刚给了你一个想法,你可以使用相同的概念转换代码。 - Tuseef ashraf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接