ZetCode

Ada sorting

last modified November 23, 2026

Sorting puts the elements of an array into an order defined by a comparison. Small arrays are often sorted by insertion, large ones by quicksort or merge sort, and Ada's standard library provides a generic sort that works with any array and any "<". This article builds the three classic algorithms from the smallest step up, then sorts an array of records without writing the algorithm again.

Inserting one element

Insertion sort grows a sorted prefix one element at a time. The program below starts with the prefix 1, 3, 5, 7 and a free slot at the end, then inserts 4 into its place. The while loop shifts larger values one slot to the right until the correct position is free.

insert_one.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Insert_One is
   type Numbers is array (Positive range <>) of Integer;
   Data : Numbers := [1, 3, 5, 7, 0];
   Key  : constant Integer := 4;
   J    : Integer := 4;
begin
   while J >= Data'First and then Data (J) > Key loop
      Data (J + 1) := Data (J);
      J := J - 1;
   end loop;
   Data (J + 1) := Key;
   for X of Data loop
      Put (Integer'Image (X));
   end loop;
   New_Line;
end Insert_One;

J walks left while the value at J is larger than the key. The and then is essential: when J reaches 0, the first condition is false and the array access is not evaluated. After the loop, J + 1 is the first free slot, so the key goes there.

$ gnatmake -gnat2022 -gnatwa insert_one.adb
$ ./insert_one
 1 3 4 5 7

Insertion sort

The full algorithm repeats that insertion for every position from the second element to the last. The first element is already a sorted prefix of length one, and each pass extends the prefix by one. Key saves the element before the shifting overwrites it.

insertion_sort.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Insertion_Sort is
   type Numbers is array (Positive range <>) of Integer;
   Data : Numbers := [7, 3, 9, 1, 5, 8, 2];

   procedure Print (A : Numbers) is
   begin
      for X of A loop
         Put (Integer'Image (X));
      end loop;
      New_Line;
   end Print;

   procedure Sort (A : in out Numbers) is
      Key : Integer;
      J   : Integer;
   begin
      for I in A'First + 1 .. A'Last loop
         Key := A (I);
         J := I - 1;
         while J >= A'First and then A (J) > Key loop
            A (J + 1) := A (J);
            J := J - 1;
         end loop;
         A (J + 1) := Key;
      end loop;
   end Sort;
begin
   Print (Data);
   Sort (Data);
   Print (Data);
end Insertion_Sort;

Insertion sort is stable, so equal elements keep their relative order, and it needs no extra array. Its worst case is quadratic, which shows on data that is sorted in reverse; on nearly sorted data it is close to linear because the inner loop hardly runs. The output prints the array before and after sorting.

$ gnatmake -gnat2022 -gnatwa insertion_sort.adb
$ ./insertion_sort
 7 3 9 1 5 8 2
 1 2 3 5 7 8 9

Quicksort

Quicksort chooses a pivot, moves every smaller element to its left and every larger element to its right, and then sorts the two parts by the same method. This version takes the last element as the pivot. Partition keeps Store at the first position that does not yet belong to the smaller side.

quick_sort.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Quick_Sort is
   type Numbers is array (Positive range <>) of Integer;
   Data : Numbers := [7, 3, 9, 1, 5, 8, 2, 6, 4];

   procedure Swap (A : in out Numbers; I, J : Positive) is
      Temp : constant Integer := A (I);
   begin
      A (I) := A (J);
      A (J) := Temp;
   end Swap;

   function Partition (A : in out Numbers; Low, High : Positive) return Positive is
      Pivot : constant Integer := A (High);
      Store : Positive := Low;
   begin
      for J in Low .. High - 1 loop
         if A (J) < Pivot then
            Swap (A, Store, J);
            Store := Store + 1;
         end if;
      end loop;
      Swap (A, Store, High);
      return Store;
   end Partition;

   procedure Sort (A : in out Numbers; Low, High : Positive) is
      P : Positive;
   begin
      if Low < High then
         P := Partition (A, Low, High);
         if P > Low then
            Sort (A, Low, P - 1);
         end if;
         if P < High then
            Sort (A, P + 1, High);
         end if;
      end if;
   end Sort;
begin
   Sort (Data, Data'First, Data'Last);
   for X of Data loop
      Put (Integer'Image (X));
   end loop;
   New_Line;
end Quick_Sort;

The two recursive calls skip the pivot, which is already in its final place. The P > Low guard matters because P - 1 would be zero when the pivot is the first element, and zero is outside the Positive index subtype. Quicksort sorts in place and is fast on average, but choosing the last element as the pivot makes already sorted input its worst case.

$ gnatmake -gnat2022 -gnatwa quick_sort.adb
$ ./quick_sort
 1 2 3 4 5 6 7 8 9

Merge sort

Merge sort splits the array in half, sorts each half, and merges the two sorted runs into a temporary array. The merge compares the front elements and always takes the smaller one, so the combined run stays ordered. The comparison uses <=, which keeps equal elements in their original order.

merge_sort.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Merge_Sort is
   type Numbers is array (Positive range <>) of Integer;
   Data : Numbers := [7, 3, 9, 1, 5, 8, 2, 6, 4];

   procedure Sort (A : in out Numbers) is
      Temp : Numbers (A'Range);

      procedure Merge (Low, Mid, High : Positive) is
         I : Positive := Low;
         J : Positive := Mid + 1;
         K : Positive := Low;
      begin
         while I <= Mid and J <= High loop
            if A (I) <= A (J) then
               Temp (K) := A (I);
               I := I + 1;
            else
               Temp (K) := A (J);
               J := J + 1;
            end if;
            K := K + 1;
         end loop;
         while I <= Mid loop
            Temp (K) := A (I);
            I := I + 1;
            K := K + 1;
         end loop;
         while J <= High loop
            Temp (K) := A (J);
            J := J + 1;
            K := K + 1;
         end loop;
         for X in Low .. High loop
            A (X) := Temp (X);
         end loop;
      end Merge;

      procedure Split (Low, High : Positive) is
         Mid : constant Positive := Low + (High - Low) / 2;
      begin
         if Low < High then
            Split (Low, Mid);
            Split (Mid + 1, High);
            Merge (Low, Mid, High);
         end if;
      end Split;
   begin
      if A'Length > 1 then
         Split (A'First, A'Last);
      end if;
   end Sort;
begin
   Sort (Data);
   for X of Data loop
      Put (Integer'Image (X));
   end loop;
   New_Line;
end Merge_Sort;

The temporary array is declared in Sort and reused by every merge, so the recursion does not allocate a new one at each level. It has the same bounds as A, so Temp (K) lines up with the original positions. Merge sort is stable and runs in O (N log N) time in every case, but it needs the extra array, unlike quicksort. The two remaining loops copy whatever is left in either half after the main merge loop.

$ gnatmake -gnat2022 -gnatwa merge_sort.adb
$ ./merge_sort
 1 2 3 4 5 6 7 8 9

Sorting records with the generic sort

Ada.Containers.Generic_Array_Sort is a generic procedure that sorts any array whose element type has a "<". The instantiation names the index type, the element type, the array type, and optionally the comparison. Here the comparison orders players by score, highest first, and breaks ties by name.

score_sort.adb
with Ada.Containers.Generic_Array_Sort;
with Ada.Text_IO;
use Ada.Text_IO;

procedure Score_Sort is
   type Player is record
      Name  : String (1 .. 5);
      Score : Integer;
   end record;

   type Players is array (Positive range <>) of Player;
   Data : Players := [("ALICE", 90), ("BOB  ", 75),
                      ("CAROL", 90), ("DAVE ", 60)];

   function Higher (A, B : Player) return Boolean is
   begin
      if A.Score /= B.Score then
         return A.Score > B.Score;
      else
         return A.Name < B.Name;
      end if;
   end Higher;

   procedure Sort is new Ada.Containers.Generic_Array_Sort
     (Index_Type   => Positive,
      Element_Type => Player,
      Array_Type   => Players,
      "<"          => Higher);
begin
   Sort (Data);
   for P of Data loop
      Put_Line (P.Name & " " & Integer'Image (P.Score));
   end loop;
end Score_Sort;

The names have a fixed length of five characters, which is why BOB and DAVE carry trailing spaces in the aggregate. ALICE and CAROL both have 90 points, so the name comparison puts ALICE first. The output has two spaces before each score: one from the string separator and one from Integer'Image.

$ gnatmake -gnat2022 -gnatwa score_sort.adb
$ ./score_sort
ALICE  90
CAROL  90
BOB    75
DAVE   60

Next steps

The next article looks for values instead of ordering them: linear search, binary search on a sorted array, and a generic search that takes its comparison as a formal subprogram. The arrays article explains the unconstrained array types and aggregates used throughout this article.

Source

Ada Reference Manual

GNAT User's Guide

AdaCore learning resources

In this article we have inserted one element into a sorted prefix, written insertion sort, quicksort, and merge sort, and reused Ada.Containers.Generic_Array_Sort with a custom comparison on records. The recursion article explains the recursive calls in quicksort and merge sort.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Ada tutorials.