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
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.