-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathheap.cpp
More file actions
60 lines (53 loc) · 1.3 KB
/
heap.cpp
File metadata and controls
60 lines (53 loc) · 1.3 KB
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
/*
* heap.cpp
* aStar
*
* Created by Bobby's Macbook on 2/8/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include "heap.h"
void HeapType::ReheapDown( int root, int bottom ){
int maxChild, rightChild, leftChild;
leftChild = 2*root+1;
rightChild = 2*root+2;
if(leftChild <= bottom) { // left child is part of the heap
if(leftChild == bottom) // only one child
maxChild = leftChild;
else { // two children
if(elements[leftChild].f >= elements[rightChild].f)
maxChild = rightChild;
else
maxChild = leftChild;
}
if(elements[root].f > elements[maxChild].f) {
Swap(elements, root, maxChild);
ReheapDown(maxChild, bottom);
}
}
}
void HeapType::ReheapUp(int root, int bottom){
int parent;
if(bottom > root) { // tree is not empty
parent = (bottom-1)/2;
if(elements[parent].f == elements[bottom].f)
{
if( elements[parent].g < elements[bottom].g )
{
Swap(elements, parent, bottom);
ReheapUp(root, parent);
}
}
else if(elements[parent].f > elements[bottom].f) {
Swap(elements, parent, bottom);
ReheapUp(root, parent);
}
}
}
void Swap( nodeType* elements, int one, int other ){
nodeType holder;
//use a holder to swap the two nodeTypes
holder = elements[one];
elements[one] = elements[other];
elements[other] = holder;
}