问题
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 and smallest numbers in my array?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/7129220/how-to-find-the-smallest-and-biggest-number-in-an-array