Tutorial

Basic Sorting

Sorting is used in arrays to making searching for information quicker.  When you start writing programs for storing data, you will use programs for sorting.
 

with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure Sort is
   Max_Elements : constant := 5;
   subtype Index is Integer range 1 .. Max_Elements;
   type Integer_Array is array (Index) of Integer;
   A : Integer_Array;
   Num_Elements : Natural := 0;
   L : Index;
   Temp : integer;
begin
   Put_Line ("Enter 5 whole numbers seperated by a space");
   while Num_Elements < Max_Elements loop
      Num_Elements:= Num_Elements + 1;
      Get (A(Num_Elements));
   end loop;

for J in 1 .. Num_Elements loop
   L:=J;
   for I in J + 1 .. Num_Elements loop
      if A(I) < A(L) then
         L:=I;
      end if;
   end loop;

   Temp := A(J);
   A(J) := A(L);
   A(L) := Temp;
end loop;

    New_Line;
    for J in 1 .. Num_Elements loop
       Put (A(J));
    end loop;
end Sort;

Figure 1   Basic sorting program example

When this sorting program is run, the ouput is as follows:

Enter 5 whole numbers seperated by a space
5 -9 22 0 -999
    -999  -9  0  5  22
 

Go to the Tutorial Table of Contents