Sorting in Ada

In Ada, we can use the Ada.Containers.Generic_Array_Sort package to sort arrays. Let’s look at how to sort built-in types.

with Ada.Text_IO;
with Ada.Containers.Generic_Array_Sort;

procedure Sorting is
   package IO renames Ada.Text_IO;

   -- Sorting for strings
   type String_Array is array (Positive range <>) of String (1 .. 1);
   Strs : String_Array := ("c", "a", "b");

   procedure Sort_Strings is new Ada.Containers.Generic_Array_Sort
     (Index_Type   => Positive,
      Element_Type => String,
      Array_Type   => String_Array);

   -- Sorting for integers
   type Int_Array is array (Positive range <>) of Integer;
   Ints : Int_Array := (7, 2, 4);

   procedure Sort_Ints is new Ada.Containers.Generic_Array_Sort
     (Index_Type   => Positive,
      Element_Type => Integer,
      Array_Type   => Int_Array);

   -- Function to check if an array is sorted
   function Is_Sorted (Arr : Int_Array) return Boolean is
   begin
      for I in Arr'First .. Arr'Last - 1 loop
         if Arr (I) > Arr (I + 1) then
            return False;
         end if;
      end loop;
      return True;
   end Is_Sorted;

begin
   -- Sort strings
   Sort_Strings (Strs);
   IO.Put ("Strings: ");
   for S of Strs loop
      IO.Put (S & " ");
   end loop;
   IO.New_Line;

   -- Sort integers
   Sort_Ints (Ints);
   IO.Put ("Ints:    ");
   for I of Ints loop
      IO.Put (Integer'Image (I) & " ");
   end loop;
   IO.New_Line;

   -- Check if sorted
   IO.Put_Line ("Sorted:  " & Boolean'Image (Is_Sorted (Ints)));
end Sorting;

In this Ada example, we’re using the Ada.Containers.Generic_Array_Sort package to sort arrays of strings and integers. We define separate procedures for sorting strings and integers because Ada’s generic sorting algorithm needs to be instantiated for each type we want to sort.

We also implement a simple Is_Sorted function to check if an array is in sorted order, as Ada doesn’t provide this functionality out of the box.

To run this program, save it as sorting.adb and use the following commands:

$ gnatmake sorting.adb
$ ./sorting
Strings: a b c 
Ints:    2 4 7 
Sorted:  TRUE

This example demonstrates how to sort built-in types in Ada and check if an array is sorted. Ada’s strong typing system requires us to be explicit about the types we’re working with, which can lead to more verbose code but also helps catch errors at compile-time.