home *** CD-ROM | disk | FTP | other *** search
- (*
- ╔═══════════════════════════════════════════════════════════════════════════╗
- ║ Turbo Pascal 6.0 Include File : SDSORT07.INC ║
- ╟───────────────────────────────────────────────────────────────────────────╢
- ║ Program : SORTDEMO.PAS ║
- ╟───────────────────────────────────────────────────────────────────────────╢
- ║ Version : 1.0 ║
- ╟───────────────────────────────────────────────────────────────────────────╢
- ║ Copyright (c) 1992 by Jon S. Russell ║
- ╟───────────────────────────────────────────────────────────────────────────╢
- ║ Heap sort routines for SORTDEMO.PAS ║
- ╚═══════════════════════════════════════════════════════════════════════════╝
- *)
- procedure HeapSort (var Info : InfoType);
- var
- Index : IndexType;
-
- (*───────────────────────────────────────────────────────────────────────*)
-
- procedure ReHeapDown (var Heap : InfoType;
- Root : IndexType;
- Bottom : IndexType);
-
- (* Restores the heap order property to the subtree starting *)
- (* at Root. On invocation or ReHeapDown, the order property *)
- (* is violated (if at all) only by root node. *)
-
- var
- MaxChild : IndexType; (* index of child with larger value *)
- RightChild : IndexType; (* index of the right child node *)
- LeftChild : IndexType; (* index of the left child node *)
-
- begin (* ReHeapDown *)
- LeftChild := Root * 2;
- RightChild := Root * 2 + 1;
-
- (* Check for Base Case 1: Heap[Root] is a leaf *)
- if LeftChild <= Bottom then
- begin (* Heap[Root] is not a leaf *)
- if LeftChild=Bottom
- then (* MaxChild := index of child with larger value *)
- MaxChild := LeftChild
- else (* pick the greater of the two children *)
- if (Heap.List[LeftChild].Key > Heap.List[RightChild].Key)
- then MaxChild := LeftChild
- else MaxChild := RightChild;
-
- (* Check for Base Case 2: order property intact *)
- if Heap.List[Root].Key < Heap.List[MaxChild].Key then
- begin (* General Case: swap and reheap *)
- Swap(Heap, Root, MaxChild);
- ReHeapDown(Heap, MaxChild, Bottom);
- end;
- end;
- end; (* ReHeapDown *)
-
- (*───────────────────────────────────────────────────────────────────────*)
-
- begin (* HeapSort *)
- (* Build the original heap from the unsorted elements. *)
- for Index := (Info.Len div 2) downto 1 do
- ReHeapDown(Info, Index, Info.Len);
-
- (* Sort the elements in the heap by swapping the root *)
- (* (current largest) value with the last unsorted *)
- (* value, then reheaping remaining part of the list. *)
- (* Loop Invariant: List[1] .. List[Index] represents *)
- (* a heap AND List[Index+1] .. List[Len] are *)
- (* sorted in ascending order. *)
- for Index := Info.Len downto 2 do
- begin
- Swap(Info, 1, Index);
- ReHeapDown(Info, 1, Index-1);
- end; (* for *)
-
- Info.Sorted := true;
- end; (* HeapSort *)
-
- (*─────────────────────────────────────────────────────────────────────────*)
-