Find Maximum Value in Array in Ada

2019-07-31 03:11发布

问题:

I am doing an Ada program with lots of different functions messing with arrays, i got all my sorting functions going, i am now stuck on retrieving the maximum value in an array using a loop invariant to design the loop for that function. any help?

回答1:

How about simply looping over the whole array?

something like this:

function Get_Maximum (Of : My_Array_Type) return Element_Type is
   Maximum : Element_Type := Of (Of'First);
begin
   for I in Of'First + 1 .. Of'Last loop
      if Of (I) > Maximum then
         Maximum := Of (I);
      end if;
   end loop;
   return Maximum;
end Get;

will raise an exception if the array is empty, but this is left as an excercise for the reader, if those cases are needed.



回答2:

oenone is correct for an unsorted array, but as you state you have your sorting functions working correctly, why not sort the array, and then use:

Maximum := Of(Of'Last);