Jump to content

Sort using a custom comparator: Difference between revisions

no edit summary
No edit summary
Line 2:
 
Sort an array (or list) of strings in order of descending length, then in ascending lexicographic order. Use a sorting facility provided by the language/library, combined with your own callback comparison function.
==[[Ada]]==
 
[[category:Ada]]
'''Compiler:'''[[GNAT]] GPL 2006
===Comparator_Package.ads===
package Comparator_Package is
procedure Move_String(From : Natural; To : Natural);
function Lt (Left, Right : Natural) return Boolean;
function Gt (Left, Right : Natural) return Boolean;
procedure Print_Array;
end Comparator_Package;
===Comparator_Package.adb===
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_Io; use Ada.Text_Io;
package body Comparator_Package is
type Data is array(Natural range <>) of Unbounded_String;
Strings : Data := (Null_Unbounded_String,
To_Unbounded_String("this"),
To_Unbounded_String("is"),
To_Unbounded_String("a"),
To_Unbounded_String("set"),
To_Unbounded_String("of"),
To_Unbounded_String("strings"),
To_Unbounded_String("to"),
To_Unbounded_String("sort"));
procedure Move_String(From : Natural; To : Natural) is
begin
Strings(To) := Strings(From);
end Move_String;
function Lt (Left, Right : Natural) return Boolean is
begin
return Strings(Left) < Strings(Right);
end Lt;
function Gt (Left, Right : Natural) return Boolean is
begin
return Strings(Left) > Strings(Right);
end Gt;
procedure Print_Array is
begin
for I in 1..Strings'Last loop
Put_Line(To_String(Strings(I)));
end loop;
end Print_Array;
end Comparator_Package;
===Custom_Comparator.adb===
with Gnat.Heap_Sort_A; use Gnat.Heap_Sort_A;
with Ada.Text_Io; use Ada.Text_Io;
with Comparator_Package; use Comparator_Package;
procedure Custom_Comparator is
begin
Put_Line(" Unsorted Array:");
Print_Array;
New_Line;
Put_Line(" Sorted in descending order:");
Sort(8, Move_String'access, Lt'access);
Print_Array;
New_Line;
Put_Line(" Sorted in Ascending order:");
Sort(8, Move_String'access, Gt'access);
Print_Array;
end Custom_Comparator;
===Output File===
Unsorted Array:
this
is
a
set
of
strings
to
sort
Sorted in descending order:
a
is
of
set
sort
strings
this
to
Sorted in Ascending order:
to
this
strings
sort
set
of
is
a
==[[C]]==
[[Category:C]]
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.