Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program main;
- uses math;
- type
- TDynamic = array of Integer;
- procedure Output(Const arr: TDynamic);
- var
- i: Integer;
- begin
- for i := Low(arr) to High(arr) do
- write(arr[i], ' ');
- writeln;
- end;
- procedure Heapify(Var arr: TDynamic; Const index, heapLen: Integer);
- var
- left, right, tmp: Integer;
- begin
- left := 2 * index + 1;
- right := 2 * index + 2;
- if (right < heapLen) and (arr[right] > arr[index]) then
- begin
- tmp := arr[right];
- arr[right] := arr[index];
- arr[index] := tmp;
- Heapify(arr, right, heapLen);
- end;
- if (left < heapLen) and (arr[left] > arr[index]) then
- begin
- tmp := arr[left];
- arr[left] := arr[index];
- arr[index] := tmp;
- Heapify(arr, left, heapLen);
- end;
- end;
- procedure BuildMaxHeap(Var arr: TDynamic);
- var
- i: Integer;
- begin
- for i := length(arr) - 1 downto 0 do
- Heapify(arr, i, length(arr));
- end;
- procedure InitHeap(Var arr: TDynamic; Const size: Integer);
- var
- i: Integer;
- begin
- SetLength(arr, size);
- for i := Low(arr) to High(arr) do
- begin
- write(i, ' elem = ');
- readln(arr[i]);
- end;
- BuildMaxHeap(arr)
- end;
- function PopElem(Var arr: TDynamic; heapLen: Integer): Integer;
- begin
- PopElem := arr[0];
- arr[0] := arr[heapLen - 1];
- heapLen := heapLen - 1;
- Heapify(arr, 0, heapLen);
- SetLength(arr, heapLen);
- end;
- procedure InsertElem(Var arr: TDynamic; Const elem: Integer);
- var
- InsInd: Integer;
- parent: Integer;
- tmp: Integer;
- StopFlag: Boolean = False;
- begin
- SetLength(arr, length(arr) + 1);
- InsInd := length(arr) - 1;
- arr[InsInd] := elem;
- while (InsInd <> 0) or (not StopFlag) do
- begin
- parent := floor(InsInd / 2);
- if arr[parent] < arr[InsInd] then
- begin
- tmp := arr[parent];
- arr[parent] := arr[InsInd];
- arr[InsInd] := tmp;
- InsInd := parent;
- end
- else
- StopFlag := True;
- end;
- end;
- {
- M A I N ! ! !
- }
- var
- N: Integer;
- heap: TDynamic;
- tmp: Integer;
- begin
- write('Enter N: ');
- readln(N);
- InitHeap(heap, N);
- Output(heap);
- tmp := PopElem(heap, length(heap));
- writeln(tmp);
- Output(heap);
- tmp := 10;
- InsertElem(heap, tmp);
- Output(heap);
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement