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

后端 未结 2 606
夕颜
夕颜 2021-01-02 22:16

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

2条回答
  •  醉话见心
    2021-01-02 23:05

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

提交回复
热议问题