summaryrefslogtreecommitdiff
path: root/sort/stooge.adb
blob: fb1077dd6c53f975a441afbe4c21086f7f898c2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

with Ada.Text_IO; use Ada.Text_IO;

package body Stooge is


    procedure Swap(A, B : in out Element_T) is
        Temp : Element_T;
    begin
        Temp := A;
        A := B;
        B := Temp;
    end Swap;


    procedure Sort(Arr : in out Array_T) is
    begin
        if Arr'Length <= 1 then
            return;
        end if;

        if Arr(Arr'First) > Arr(Arr'Last) then
            Swap(Arr(Arr'First), Arr(Arr'Last));
        end if;

        if Arr'Length >= 3 then
            declare
                Third : Integer := Arr'Length / 3;
                Arr_One_Third : Index_T := Index_T'Val(Index_T'Pos(Arr'First) + Third);
                Arr_Two_Third : Index_T := Index_T'Val(Index_T'Pos(Arr'Last) - Third);
            begin
                Sort(Arr(Arr'First .. Arr_Two_Third));
                Sort(Arr(Arr_One_Third .. Arr'Last));
                Sort(Arr(Arr'First .. Arr_Two_Third));
            end;
        end if;
    end Sort;


end Stooge;