【问题标题】:How to find the smallest and biggest number in an array?如何找到数组中的最小和最大数字?
【发布时间】:2011-10-31 01:10:30
【问题描述】:

你好,我怎样才能在delphi中找到最小和最大的数字?

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

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

【问题讨论】:

    标签: arrays delphi search delphi-2007


    【解决方案1】:

    只需以线性方式循环遍历数组。为最小值保留一个变量,为最大值保留一个变量。将两者都初始化为数组中的第一个值。然后对于每个元素,如果该元素分别小于或大于最小值或最大值,则更新最小值或最大值。

    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。

    请注意,您同样可以使用数学单元中的 MinValue 和 MaxValue 例程。

    【讨论】:

    • 我想我们是同时打字的!我更喜欢你的初始化,但我更喜欢更紧凑的 for..in 结构,尽管这取决于他的 Delphi 版本是否受支持。
    • +1 对于MinValueMaxValue。还有MinIntValueMaxIntValue
    • @ngln 谢谢你,当然你是对的,我习惯使用浮点数据。
    • 但我的数字是 int64。当我发现 minvalue 时出现问题,即 -112322654564545 不是整数值。
    【解决方案2】:

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

    这是一个代码 sn-p。根据您的说明,我已编辑代码以使用 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;
    

    这个实现,类似于大卫的回答,使用第一个数组值作为初始值。这假设数组至少有一个元素。另请注意,循环可以从 Low(Data) + 1 开始并保存一个不必要的比较。对于您描述的数据,每个数组中有 100 个元素,您最多可以提高 1% 的速度。

    如果性能无关紧要,那么 MinIntValue 和 MaxIntValue 会更简洁。如果您自己滚动,那么您只需遍历数组一次而不是两次。

    【讨论】:

      【解决方案3】:

      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.

      【讨论】:

      • 问题特别要求使用Delphi解决方案。您的代码是 JavaScript,那么它有什么帮助?
      • 我刚刚给了你一个想法,你可以使用相同的概念转换代码
      猜你喜欢
      • 2018-08-27
      • 2011-04-17
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 2019-09-10
      • 2013-04-24
      相关资源
      最近更新 更多