summaryrefslogtreecommitdiff
path: root/sort/selection.adb
blob: 1b49769bb49815afcf82f93aecc8c851681218b8 (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
42


package body Selection is


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


    function Find_Largest(Arr : in Array_T) return Index_T is
        Max : Index_T;
    begin
        Max := Arr'First;
        for P in Index_T range Index_T'Succ(Arr'First) .. Arr'Last loop
            if Arr(P) > Arr(Max) then
                Max := P;
            end if;
        end loop;
        return Max;
    end Find_Largest;


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

        Largest := Find_Largest(Arr);
        Swap( Arr(Arr'Last), Arr(Largest) );
        Sort( Arr(Arr'First .. Index_T'Pred(Arr'Last)) );
    end Sort;


end Selection;