Constraint Error running Heapify SiftDown

83 Views Asked by At

I am writing this code in Ada for a class where we have to teach ourselves the code. I understand heap sort, but the Ada syntax is really confusing me. I don't understand why I am getting a constraint error in this sort function. Essentially we have to pass array "A" into this procedure, and it should organize it. I get the constraint error at siftDown(A(Start...A'Last));

Thank you in advance

Procedure sort_3(A : in out array_type) is

  procedure swap(Left : in out Integer; Right : in out Integer) is
     temp : Integer;
  begin
     temp := Left;
     Left := Right;
     Right := Temp;
  end swap;
  
  procedure siftDown(A : in out array_type) is
     Count : Integer := 1;
     root : Integer := Integer'Pos(A'First);
     child : Integer := Integer'Pos(A'Last);
     last : Integer := Integer'Pos(A'Last);
  begin
     while root * 2 + 1 <= last loop
        child := root * 2 + 1;
        if child + 1 <= last and then A(Integer'Val(child)) < A(Integer'Val(child + 1)) then
           child := child + 1;
        end if;
        if A(Integer'Val(root)) < A(Integer'Val(child)) then
           swap(A(Integer'Val(root)), A(Integer'Val(child)));
           root := child;
        else
           exit;
        end if;
     end loop;
  end siftDown;

  procedure heapify(A : in out array_type) is
     Count : Integer := 0;
     First_Pos : Integer;
     Last_Pos  : Integer;
     Start     : Integer;
  begin
     First_Pos := A'First;
     Last_Pos  := A'Last;
     Start     := Integer'Val((Last_Pos - First_Pos + 1) / 2);
      loop
       siftDown(A(Start...A'Last));
        if Start > Integer'First then
           Start := Integer'Pred(Start);
       else
           exit;
        end if;
     end loop;
  end heapify;
  Last_Index : Integer := Integer'Last;
  
   begin
  heapify(A);
  while Last_Index > Integer'First loop
     swap(A(Last_Index), A(A'First));
     Last_Index := Integer'Pred(Last_Index);
     siftDown(A(A'First..Last_Index));
  end loop;
 
end sort_3;
2

There are 2 best solutions below

1
On

You have a syntax error in the code - an extra dot in A(Start...A'Last).

The syntax A(Start..A'Last) means a slice, part of array from Start to the last element. The Constraint_Error means that Start not in array bounds. Try to add

Ada.Text_IO.Put_Line (Start'Image);

before that line and you will see Start values and when it became out of the A'Range.

0
On

Your code has some references to Integer'First and Integer'Last, which are huge values that have nothing to do with the array A and its values. I'm pretty sure you should use A'First and A'Last instead.

Also a note on style: Using the same identifier, "A", for the parameter of the local (inner, nested) procedures as for the parameter "A" of the containing (outer) procedure, when these arrays can be different, invites confusion and errors. Better to use different identifiers.