~ubuntu-branches/ubuntu/utopic/mricron/utopic

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
{ ******************************************************************
  Quick sort
  ****************************************************************** }

unit uqsort;

interface

uses
  utypes;

procedure QSort(X : PVector; Lb, Ub : Integer);
{ ------------------------------------------------------------------
  Sorts the elements of vector X in increasing order (quick sort)
  ------------------------------------------------------------------ }

procedure DQSort(X : PVector; Lb, Ub : Integer);
{ ------------------------------------------------------------------
  Sorts the elements of vector X in decreasing order (quick sort)
  ------------------------------------------------------------------ }

implementation

procedure QSort(X : PVector; Lb, Ub : Integer);
{ Quick sort in ascending order - Adapted from Borland's BP7 demo }

    procedure Sort(L, R : Integer);
    var
      I, J : Integer;
      U, V : Float;
    begin
      I := L;
      J := R;
      U := X^[(L + R) div 2];
      repeat
        while X^[I] < U do I := I + 1;
        while U < X^[J] do J := J - 1;
        if I <= J then
          begin
            V := X^[I]; X^[I] := X^[J]; X^[J] := V;
            I := I + 1; J := J - 1;
          end;
      until I > J;
      if L < J then Sort(L, J);
      if I < R then Sort(I, R);
    end;

begin
  Sort(Lb, Ub);
end;

procedure DQSort(X : PVector; Lb, Ub : Integer);
{ Quick sort in descending order - Adapted from Borland's BP7 demo }

    procedure Sort(L, R : Integer);
    var
      I, J : Integer;
      U, V : Float;
    begin
      I := L;
      J := R;
      U := X^[(L + R) div 2];
      repeat
        while X^[I] > U do I := I + 1;
        while U > X^[J] do J := J - 1;
        if I <= J then
          begin
            V := X^[I]; X^[I] := X^[J]; X^[J] := V;
            I := I + 1; J := J - 1;
          end;
      until I > J;
      if L < J then Sort(L, J);
      if I < R then Sort(I, R);
    end;

begin
  Sort(Lb, Ub);
end;

end.