How to find the smallest and biggest number in an array?

后端 未结 2 584
夕颜
夕颜 2021-01-02 22:16

Hello how can I find the smallest and biggest number in delphi?

Suppose I have 10 different numbers stored in an array:

How can I find the biggest number an

相关标签:
2条回答
  • 2021-01-02 22:44

    Iterate through the array comparing to the previous found min and max.

    Here is a code snippet. Following your clarification, I have edited the code to use 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;
    

    It's interesting to note that MaxIntValue in Math.pas is implemented as:

    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;
    

    This implementation, similar to David's answer, uses the first array value as the initial value. This assumes that the array has at least one element. Note also that the loop can then start at Low(Data) + 1 and save one unnecessary comparison. For the data you have described, with 100 elements in each array, you would get a 1% speed improvement, at best.

    If performance doesn't matter then MinIntValue and MaxIntValue will be more concise. If you roll your own, then you are only iterating through the array once instead of twice.

    0 讨论(0)
  • 2021-01-02 23:05

    Simply loop through the array in linear fashion. Keep a variable for the min value and one for the max values. Initialise both to the first value in the array. Then for each element, update the min or max value if that element is less than or greater than the min or max value respectively.

    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;
    

    Obviously this code assumes Count>0.

    Note that you could equally use the MinValue and MaxValue routines from the Math unit.

    0 讨论(0)
提交回复
热议问题