--  Verada predefined library: a stable sort, proved. It sorts an array by an integer key
--  of its elements and returns, beside the sorted array, where each element came from
--  (Moved), which is the proof that the result is a permutation of the array given and that
--  elements of equal key keep their order. A client that needs neither fact passes a scratch
--  array for Moved.
generic
   type Index_Type is range <>;
   type Element_Type is private;
   type Array_Type is array (Index_Type range <>) of Element_Type;
   with function Key (Item : Element_Type) return Integer;
package Verada.Containers.Generic_Stable_Sort is
   type Index_Array is array (Index_Type range <>) of Index_Type;

   --  each element's key no larger than any after it
   function Sorted (A : Array_Type) return Boolean is
     (for all I in A'Range => (for all J in A'Range => (if I < J then Key (A (I)) <= Key (A (J)))));

   --  Moved names each of A's places once
   function Is_Permutation (Moved : Index_Array) return Boolean is
     ((for all I in Moved'Range => Moved (I) in Moved'Range)
      and then (for all I in Moved'Range => (for all J in Moved'Range => (if I /= J then Moved (I) /= Moved (J)))));

   --  A sorted by key; A (I) was A'Old (Moved (I)), each place named once; of elements of
   --  equal key, the earlier came from earlier
   procedure Sort (A : in out Array_Type; Moved : out Index_Array)
     with Pre => Moved'First = A'First and then Moved'Last = A'Last,
          Post => Sorted (A)
                  and then Is_Permutation (Moved)
                  and then (for all I in A'Range => A (I) = A'Old (Moved (I)))
                  and then (for all I in A'Range =>
                              (for all J in A'Range => (if I < J and then Key (A (I)) = Key (A (J)) then Moved (I) < Moved (J))));
end Verada.Containers.Generic_Stable_Sort;
