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

Hi, how can I find the smallest and largest number in delphi?

Suppose I have 10 different numbers stored in an array:

How to find the largest number and smallest numbers in my array?

+6
source share
2 answers

Just swipe through the array in a linear fashion. Save the variable for the minimum value and one for the maximum values. Initialize both values ​​to the first value in the array. Then, for each element, update the minimum or maximum value if this element is less than or greater than the minimum or maximum 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 can use the MinValue and MaxValue routines from the Math module equally.

+6
source

Iterates through the array compared to the previous min and max found.

Here is a snippet of code. After clarification, I 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 is 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 value of the array as the initial value. This assumes that the array has at least one element. Also note that the loop may start with Low (Data) + 1 and save one unnecessary comparison. For the data you described, with 100 elements in each array, you will at best get a speed increase of 1%.

If performance does not matter, then MinIntValue and MaxIntValue will be more concise. If you roll back your own, you only iterate through the array once, not twice.

+4
source

Source: https://habr.com/ru/post/895464/


All Articles