Verada.Containers.Generic_Stable_Sort
A proved stable sort of an array by an integer key of its elements. Beside the sorted array it returns 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.
Read the family guide for how permutations and models are stated in contracts. The complete declaration page retains exact signatures/contracts; the source specification is the implementation baseline.
Availability and ownership
The body is an insertion sort by adjacent swaps, proved against the contract. It takes time proportional to the square of the length in the worst case, and no storage beyond Moved.
Import and instantiate
with Verada.Containers.Generic_Stable_Sort;
...
package Sorting is new Verada.Containers.Generic_Stable_Sort (Positive, Entry_Type, Entries, Score_Of);API 001
Index_Type (declaration) — The generic formal part: the index type, the element type, the array type over them, and the integer key an element is sorted by.
Declared interface:
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;API 002
Index_Array (declaration) — An array of the array's places, for Moved.
Declared interface:
type Index_Array is array (Index_Type range <>) of Index_Type;API 003
Sorted (declaration) — Each element's key is no larger than any after it.
Declared interface:
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)))));API 004
Is_Permutation (declaration) — Moved names each of the array's places once.
Declared interface:
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)))));API 005
Sort (declaration) — Sorts the array by key, stably, and says where each element came from.
Declared interface:
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))));