Declarative part:
        INDEX_IN_SET : INTEGER;
      begin

First the program tests the leaf conditions :

        if SET'SIZE=0 then
          W(INDEX) := 0;
          return;
        elsif SET'SIZE=1 then
          W(INDEX) := 1 + SET(1);
          return;
        end if;

The following program finds a value in the set such that exactly (SET'SIZE-1)/2 values from the set are between this value plus 1 and this value plus half the range :

      declare
        N : INTEGER;
        J : INTEGER;
      begin
        for I in 1..SET'SIZE loop
          N:=0;
          for J in 1..SET'SIZE loop
            if (SET(J)-SET(I)) mod RANGE <= (RANGE-1)/2 then 
              N := N+1;
            end if;
          end loop;
The test compares N-1 because the possible pivot value is counted.
          if N-1 = (SET'SIZE-1)/2 then
            INDEX_IN_SET := I;
            exit;
          end if;
        end loop;
      end;

INDEX_IN_SET is then the index in the list of the pivot value.

The following sets W(INDEX)

        W(INDEX) := SET(INDEX_IN_SET) + 1;
 
Then the program does the same thing for the two halves of the range delimited by W(INDEX) and W(INDEX)+RANGE/2. First the left subset:

      declare
        SUBSET : SET_OF_VALUE(1..SET'SIZE/2);
        SUBSET_INDEX : INTEGER;
        ORIGIN_VALUE : INTEGER;
      begin
        ORIGIN_VALUE := (SET(INDEX_IN_SET] + (RANGE-1)/2 
                        + 1) mod RANGE; 
        SUBSET_INDEX:=1;
        for I in 1..SET'SIZE loop
          if (SET(I)-ORIGIN_VALUE) mod RANGE) < RANGE/2 then 
            SUBSET(SUBSET_INDEX) := 
              (SET(I) - ORIGIN_VALUE) mod RANGE;
            SUBSET_INDEX := SUBSET_INDEX + 1;
          end if;
        end loop;

        ENCODE_SUBTREE(
            INDEX := INDEX +
              GREATEST_POWER_OF_2_LESSER_OR_EQUAL_TO(INDEX),
            SET := SUBSET, 
            RANGE := RANGE/2);
      end;

Then the right subset:

      declare
        SUBSET : SET_OF_VALUE(1..(SET'SIZE-1)/2);
        SUBSET_INDEX : INTEGER;
        ORIGIN_VALUE : INTEGER;
      begin
        ORIGIN_VALUE := (SET(INDEX_IN_SET] + 1) mod RANGE; 
        SUBSET_INDEX:=1;
        for I in 1..SET'SIZE loop
          if (SET(I)-ORIGIN_VALUE) mod RANGE) < RANGE/2 then 
            SUBSET(SUBSET_INDEX) := 
              (SET(I) - ORIGIN_VALUE) mod RANGE;
            SUBSET_INDEX := SUBSET_INDEX + 1;
          end if;
        end loop;
        ENCODE_SUBTREE(
          INDEX := INDEX +
            2*GREATEST_POWER_OF_2_LESSER_OR_EQUAL_TO(INDEX),
          SET := SUBSET, 
          RANGE := (RANGE-1)/2);
    end;
 
      end ENCODE_SUBTREE;

