How to find the smallest and biggest number in an array?
Hello how can I find the smallest and big开发者_运维问答gest 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?
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.
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.
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.
精彩评论