1

I've taken an Algorithm course in which the instructor has decided to use Ada as programming language tool to test our understanding. The argument was that ADA language is quite close to the Pseudo code that appears in CLRS book.

Below code is a snip for Selection sort in ADA:

   procedure Selection_Sort(Data : in out List) is
   begin
      for Destination_Index in Data'Range loop
         for Source_Index in Destination_Index + 1 .. Data'Last loop
            if Data(Source_Index) < Data(Destination_Index) then
               Swap(Data, Source_Index, Destination_Index);
            end if;
         end loop;
      end loop;
   end Selection_Sort;

The following:

for Source_Index in Destination_Index + 1 .. Data'Last loop

will cause traversing the array from given element (Data1) to last element, however if I wish to traverse from the last element to the first, the following don't seem to work.

for Source_Index in Data'Last .. Data'First loop

It would be great help if someone can help me with this trivial problem, so that I can get on with the main problem at hand, which is learning Algorithms.

Amit
  • 327
  • 1
  • 4
  • 12

1 Answers1

5

A range A .. B having A > B results in an empty range. In respect to the for cycle, there's the reverse keyword to define a descending loop (end of ARM 5.5 (9)). Hence reverse A .. B, where A < B, will result in looping from B down to A.

The rest is left up to you for the sake of learning. In order to learn something, you cannot avoid learning at the first place.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90