aboutsummaryrefslogtreecommitdiff
path: root/src/hyper/pages/HEAP.ht
blob: 974e5dcaaae55cac6bad81e97e03c53961ac71d1 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
% Copyright The Numerical Algorithms Group Limited 1992-94. All rights reserved.
% !! DO NOT MODIFY THIS FILE BY HAND !! Created by ht.awk.
\newcommand{\HeapXmpTitle}{Heap}
\newcommand{\HeapXmpNumber}{9.32}
%
% =====================================================================
\begin{page}{HeapXmpPage}{9.32 Heap}
% =====================================================================
\beginscroll
The domain \spadtype{Heap(S)} implements a priority queue of
objects of type \spad{S} such that
%-% \HDindex{priority queue}{HeapXmpPage}{9.32}{Heap}
the operation \spadfunX{extract} removes and returns
the maximum element.
%-% \HDindex{heap}{HeapXmpPage}{9.32}{Heap}
The implementation represents heaps as flexible arrays
(see \downlink{`FlexibleArray'}{FlexibleArrayXmpPage}\ignore{FlexibleArray}).
The representation and algorithms give complexity
of \texht{$O(\log(n))$}{O(log n)} for insertion and extractions,
and \texht{$O(n)$}{O(n)} for construction.

\xtc{
Create a heap of six elements.
}{
\spadpaste{h := heap [-4,9,11,2,7,-7]\bound{h}}
}
\xtc{
Use \spadfunX{insert} to add an element.
}{
\spadpaste{insert!(3,h)\bound{h1}\free{h}}
}
\xtc{
The operation \spadfunX{extract} removes and returns
the maximum element.
}{
\spadpaste{extract! h\bound{h2}\free{h1}}
}
\xtc{
The internal structure of \spad{h} has been
appropriately adjusted.
}{
\spadpaste{h\free{h2}}
}
\xtc{
Now \spadfunX{extract} elements repeatedly
until none are left, collecting the elements in a list.
}{
\spadpaste{[extract!(h) while not empty?(h)]\bound{h2}}
}
\xtc{
Another way to produce the same result is by defining
a \userfun{heapsort} function.
}{
\spadpaste{heapsort(x) == (empty? x => []; cons(extract!(x),heapsort x))\bound{f}}
}
\xtc{
Create another sample heap.
}{
\spadpaste{h1 := heap [17,-4,9,-11,2,7,-7]\bound{h1}}
}
\xtc{
Apply \spadfun{heapsort} to present elements in order.
}{
\spadpaste{heapsort h1\free{f}}
}
\endscroll
\autobuttons
\end{page}
%