数据结构 (5)
合集下载
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
else break; /* find the proper position */
}
H->Elements[ i ] = LastElement;
return MinElement;
}
11/15
4. Other Heap Operations:
§3 Binary Heap
Note: Finding any key except the minimum one will have to take a linear scan through the entire heap.
Note: Analogously, we can declare a max heap by changing the heap order property.
[1] 9 The largest key
[1] 10 The smallest key
[2] 6 [3] 3
[2] 20 [3] 83
[4] 5
return FatalError( "Out of space!!!" ); H->Capacity = MaxElements; H->Size = 0; H->Elements[ 0 ] = MinData; /* set the sentinel */ return H; }
6/15
2. Heap Order Property:
LastElement = H->Elements[ H->Size-- ]; /* take last and reset size */
for ( i = 1; i * 2 <= H->Size; i = Child ) { /* Find smaller child */
Child = i * 2;
A complete binary tree of height h has between 2h
and 2h+1 1 nodes.
h = log N
1
❖ Array Representation : BT [ n + 1 ] ( BT [ 0 ] is not used)
2
3
A
4
5
6 BT 0 7 1 2 3 4 5 6
3/15
§3 Binary Heap
1. Structure Property:
【Definition】A binary tree with n nodes and height h is complete iff its nodes correspond to the nodes numbered from 1 to n in the perfect binary tree of height h.
§3 Binary Heap
【Definition】A min tree is a tree in which the key value in each node is no larger than the key values in its children (if any). A min heap is a complete binary tree that is also a min tree.
ElementType DeleteMin( PriorityQueue H )
{ int i, Child; ElementType MinElement, LastElement;
CaWn whaetriefmthoivse it
by caodPndedinritcgiooanlnaiostteher
since a heap must be a complete binary tree.
Case 1 : new_item = 21 20 < 21
Case 2 : new_item = 17 20 > 17 10 < 17
Case 3 : new_item = 9 20 > 9 10 > 9
8/15
158 18
[4] [5]
The node which must be
removed to keep a complete binary tree.
12 < 18
find the smaller child of 18 15 < 18
T (N) = O ( log N )
10/15
§3 Binary Heap
H->Elements[ i ] = X; }
T (N) = O ( log N )
Faster than swap
9/15
DeleteMin
§3 Binary Heap
➢ Sketch of the idea: move 18 up to the root
[1] 1082 [2] 1258 [3] 20
if ( IsEmpty( H ) ) { Error( "Priority queue is empty" );
osmenditoitnewedln??
return H->Elements[ 0 ]; }
MinElement = H->Elements[ 1 ]; /* save the min element */
§3 Binary Heap
/* H->Element[ 0 ] is a sentinel */
void Insert( ElementType X, PriorityQueue H )
{
int i;
H->Element[ 0 ] is a
if ( IsFull( H ) ) {
sentthinaenlPtthehraectmoislianntieomuluapmrger
1/15
§2 Simple Implementations
Array : Insertion — add one item at the end ~ ( 1 ) Deletion — find the largest \ smallest key ~ ( n ) remove the item and shift array ~ O( n )
(1) index of
parent(i)
i
2
if i 1
None if i 1
(2)
index of
left
_
child (i )
2i
if 2i n
None if 2i n
(3)
index of
right
_
chቤተ መጻሕፍቲ ባይዱld (i )
2i
1
if 2i 1 n
None if 2i 1 n
Ordered Linked List : Insertion — find the proper position ~ O( n ) add the item ~ ( 1 ) Deletion — remove the first \ last item ~ ( 1 )
2/15
Binary Search Tree :
if (Child != H->Size && H->Elements[Child+1] < H->Elements[Child])
Child++;
if ( LastElement > H->Elements[ Child ] ) /* Percolate one level */
H->Elements[ i ] = H->Elements[ Child ];
Linked List : Insertion — add to the front of the chain ~ ( 1 ) Deletion — find the largest \ smallest key ~ ( n ) remove the item ~ ( 1 )
Ordered Array : Insertion — find the proper position ~ O( n ) shift array and add the item ~ O( n ) Deletion — remove the first \ last item ~ ( 1 )
CHAPTER 5 PRIORITY QUEUES (HEAPS)
—— delete the element with the highest \ lowest priority
§1 ADT Model
Objects: A finite ordered list with zero or more elements. Operations:
return FatalError( "Out of space!!!" ); /* Allocate the array plus one extra for sentinel */ H->Elements = malloc(( MaxElements + 1 ) * sizeof( ElementType )); if ( H->Elements == NULL )
ABCDE F
B
C
8 9 10 11 12 13 14 15
D
E
F
G
7 8 9 10 11 12 13
GH I J
H IJ
4/15
§3 Binary Heap
【Lemma】If a complete binary tree with n nodes is represented sequentially, then for any node with index i, 1 i n, we have:
Error( "Priority queue is full" ); element in the heap.
return;
}
for ( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 ) H->Elements[ i ] = H->Elements[ i / 2 ];
§2 Simple Implementations
rWeYlHaeNtelscbelWoyo,udaiwsniTytnebtsnodohystaaouaeeoelArntranlrueaeVteanetritBesboLcifeabudoeaeenragpnstgdcsferdiepstiodeantotmroarieterrdisetrsaeanteoewe,hnddgrBappksiNayaelrooustsntlnliOmooOiBitecoobwnndhpthrTudwhaecetoIeeiiet.re,Aatmnrafbrlmdtyrhsaraeodshese,iooOOeettAqnrgedt!baienmyr!uVohley(har,t’yTl☺ndetioetlLowto,anuahsuhrgtntnhoetaeohehrNc.…aataeee’latln)ensldviyfdwoafetwtnhwrdsgaeleuaeyoeebmtbl.oe?’ketdsturteitwseoeiedtepnrseao…woalnwp!ig.ltal?iyotasnk?e Thethmeinruimnaultwimmayes.ledmHaoennwgteerovoneurly…s.
PriorityQueue Initialize( int MaxElements ); void Insert( ElementType X, PriorityQueue H ); ElementType DeleteMin( PriorityQueue H ); ElementType FindMin( PriorityQueue H );
5/15
§3 Binary Heap
PriorityQueue Initialize( int MaxElements ) {
PriorityQueue H; if ( MaxElements < MinPQSize )
return Error( "Priority queue size is too small" ); H = malloc( sizeof ( struct HeapStruct ) ); if ( H ==NULL )
A max heap
[4] 50
A min heap
7/15
3. Basic Heap Operations:
insertion
➢ Sketch of the idea:
§3 Binary Heap
[1] 190 [2] 12 [3] 21907
15 18 21170
[4] [5] [6]
The only possible position for a new node