Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 968
dnaz Avatar asked Aug 20 '11 02:08

dnaz


1 Answers

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.

like image 154
David Heffernan Avatar answered Oct 19 '22 14:10

David Heffernan