Sorting by Functions in Ada
In Ada, we can implement custom sorting functions using generics and the Ada.Containers.Generic_Array_Sort package. Here’s an example of custom sorts in Ada:
with Ada.Text_IO;
with Ada.Containers.Generic_Array_Sort;
with Ada.Strings.Unbounded;
procedure Sorting_By_Functions is
use Ada.Text_IO;
use Ada.Strings.Unbounded;
type Fruit_Array is array (Positive range <>) of Unbounded_String;
Fruits : Fruit_Array := (To_Unbounded_String("peach"),
To_Unbounded_String("banana"),
To_Unbounded_String("kiwi"));
function Length_Compare (Left, Right : Unbounded_String) return Boolean is
begin
return Length(Left) < Length(Right);
end Length_Compare;
procedure Sort_Fruits is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive,
Element_Type => Unbounded_String,
Array_Type => Fruit_Array,
"<" => Length_Compare);
type Person is record
Name : Unbounded_String;
Age : Natural;
end record;
type Person_Array is array (Positive range <>) of Person;
People : Person_Array :=
((Name => To_Unbounded_String("Jax"), Age => 37),
(Name => To_Unbounded_String("TJ"), Age => 25),
(Name => To_Unbounded_String("Alex"), Age => 72));
function Age_Compare (Left, Right : Person) return Boolean is
begin
return Left.Age < Right.Age;
end Age_Compare;
procedure Sort_People is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive,
Element_Type => Person,
Array_Type => Person_Array,
"<" => Age_Compare);
begin
-- Sort fruits by length
Sort_Fruits(Fruits);
Put_Line("Sorted fruits:");
for Fruit of Fruits loop
Put_Line(To_String(Fruit));
end loop;
New_Line;
-- Sort people by age
Sort_People(People);
Put_Line("Sorted people:");
for Person of People loop
Put_Line(To_String(Person.Name) & ": " & Person.Age'Image);
end loop;
end Sorting_By_Functions;In this Ada example, we implement custom sorting for both strings (fruits) and a custom type (Person). Here’s a breakdown of the code:
We define a
Fruit_Arraytype and create an array of fruits usingUnbounded_Stringfor flexibility.We implement a
Length_Comparefunction that compares two strings based on their length.We use
Ada.Containers.Generic_Array_Sortto create a sorting procedureSort_Fruitsthat uses our custom comparison function.Similarly, we define a
Personrecord type and aPerson_Array, and create an array of people.We implement an
Age_Comparefunction to comparePersonrecords based on their age.We create another sorting procedure
Sort_PeopleusingGeneric_Array_Sortwith our customAge_Comparefunction.In the main procedure, we sort both the fruits and people arrays using our custom sorting procedures and print the results.
This example demonstrates how to implement custom sorting in Ada using generics and the Generic_Array_Sort package. It allows for flexible sorting of both built-in types and custom record types based on any criteria we define.
To compile and run this Ada program:
$ gnatmake sorting_by_functions.adb
$ ./sorting_by_functionsThis will output the sorted fruits by length and people by age.