formatted to Github Markdown syntax by Ryan Peters
const int MAX{100};
void inorderTraverse(void visit(ItemType&)) const;
bool add(const ItemType& item);
// assume getName is a member function and returning a reference
// to a private variable in the class
const string& getName() const;
Do not return a reference or pointer to a local variable
// read backwards: ptr is a pointer to an integer constant
// ptr cannot be used to change the value
const int * ptr;
https://isocpp.org/wiki/faq/const-correctness
graphical object
sdraw()
functionvirtual void draw() const
void draw() const override
graphical object
and use go->draw()
to get the correct draw functionhttp://www.cplusplus.com/doc/tutorial/polymorphism/
MaxHeap: Complete binary tree whose root is greater than its children
MinHeap: …
Not a binary search tree!
We know the index of each node based on level i
- left: 2 * i + 1
- right: 2 * i + 2
- parent: (i - 1) / 2
Keep track of itemcount
and maxItems
void heapCreate()
{
// can simplify as itemCount / 2
for (int index = itemCount - 1; index >= 0; index--)
{
heapRebuild(index);
}
} // end heapCreate
void heapRebuild(const int subTreeNodeIndex)
{
if (!isLeaf(subTreeNodeIndex))
{
// Find larger child
int leftChildIndex = ...
int rightChildIndex = ...
int largerChildIndex = ...
// Swap with larger child if node value is smaller
if (items[largerChildIndex] > items[subTreeNodeIndex])
{
swap(items[largerChildIndex], items[subTreeNodeIndex]);
// Continue with the recursion at that child
heapRebuild(largerChildIndex);
} // end if
} // end if
} // end heapRebuild
Highest priority is at the root of MaxHeap
If we know the maximum number of items in priority queue, heap is better
Heap is blanced, BST can become unbalanced degrading performance
If multiple items have the same priority, we can maintain a list at the node
When last item in the list deleted, node is deleted
Start with array [25 30 20 80 40 60]
Adjacency Matrix
Adjacency List
dfs(v: Vertex) {
s = a new stack
s.push(v)
Mark v as visited
while (!s.isEmpty())
if (no unvisited adj to vertex on top of stack)
s.pop()
else
Select unvisited adj to vertex on top
s.push(u)
Mark u as visited
}
bfs(v: Vertex) {
q = new queue
q.enqueue(v)
Mark v as visited
while (!q.isEmpty())
q.dequeue(w)
for (each unvisited vertex u adjacent to w)
Mark u as visited
q.enqueue(u)
}