summaryrefslogtreecommitdiff
path: root/sort/quick.adb
blob: 4586b3b7ace2d3bf3b00e0a4edb3e41f1f73b928 (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
46
47
48
49


package body Quick is


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


    procedure In_Place(Arr : in out Array_T) is
        Pivot, Left, Right : Index_T;
    begin
        if Arr'Length <= 1 then
            return;
        end if;

        Pivot := Arr'First;
        Left := Index_T'Succ(Pivot);
        Right := Arr'Last;

        loop
            while not (Arr(Left) > Arr(Pivot)) and Left < Arr'Last loop
                Left := Index_T'Succ(Left);
            end loop;
            while Arr(Right) > Arr(Pivot) and Right > Arr'First loop
                Right := Index_T'Pred(Right);
            end loop;
            exit when Left >= Right;
            Swap(Arr(Left), Arr(Right));
        end loop;

        Swap(Arr(Pivot), Arr(Right));

        if Right > Arr'First then
            In_Place( Arr(Arr'First .. Index_T'Pred(Right)) );
        end if;
        if Right < Arr'Last then
            In_Place( Arr(Index_T'Succ(Right) .. Arr'Last) );
        end if;
    end In_Place;


end Quick;