summaryrefslogtreecommitdiff
path: root/sort/cocktail.adb
blob: ecc9e82642dda71b7590b5f2a993310faf7dabfe (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
43
44
45


package body Cocktail 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) is
        Swapped : Boolean;
    begin
        if Arr'Length <= 1 then
            return;
        end if;

        loop
            Swapped := False;
            for I in Index_T range Arr'First .. Index_T'Pred(Arr'Last) loop
                if Arr(I) > Arr(Index_T'Succ(I)) then
                    Swap( Arr(I), Arr(Index_T'Succ(I)) );
                    Swapped := True;
                end if;
            end loop;
            exit when not Swapped;

            Swapped := False;
            for I in Index_T reverse range Index_T'Succ(Arr'First) .. Arr'Last loop
                if Arr(Index_T'Pred(I)) > Arr(I) then
                    Swap( Arr(Index_T'Pred(I)), Arr(I) );
                    Swapped := True;
                end if;
            end loop;
            exit when not Swapped;
        end loop;
    end Sort;


end Cocktail;