about summary refs log tree commit diff
path: root/2ndary/12/TP-ThanhHoá-2009/sortnfind.pas
blob: 52e8d6b3ae24f9e201206788322555cca756bb9f (plain) (blame)
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
82
83
unit sortnfind;

interface

  type
    intar = array of smallint;

  procedure qsort(var a : intar);

  function binin(
    a: intar;
    x: smallint
  ): boolean;

implementation

  procedure qsort(var a : intar);

    procedure sort(l, r: longint);
      var
        i, j, x, y: longint;

      begin
        i := l;
        j := r;
        x := a[(l + r) div 2];

        repeat
          while a[i] < x do
            inc(i);

          while x < a[j] do
            dec(j);

          if i <= j then
            begin
              y := a[i];
              a[i] := a[j];
              a[j] := y;
              inc(i);
              j := j - 1
            end
        until i > j;

        if l < j then
          sort(l, j);

        if i < r then
          sort(i, r)
      end;

    begin
       sort(0, length(a) - 1)
    end;


  function binin(
    a: intar;
    x: smallint
  ): boolean;

    var
      l, h, mid: word;

    begin
      l := 0;
      h := length(a) - 1;

      while l <= h do
        begin
          mid := (l + h) div 2;
          if x = a[mid] then
            exit(true)
          else if x < a[mid] then
            h := mid - 1
          else
            l := mid + 1
        end;

      binin := false
    end;

end.