CPSC 221

Priority Queues, continued

This image reminds us of a ________________, which is one way we can implement ADT
______________________, whose functions include ______________ and ________________,
with running times ______________________.

Today

Announcements

  • Examlet 7 is this week: AVL trees and B-trees (no hashing)
  • PA3 is due Monday 11/23
  • Lab Hash is due Sunday 11/22


Today:

  • Heaps: insert and removeMin, continued
  • Building a heap all at once
  • heapSort

Heap Explorer

Code:

void heap<T>::insert(const T & key) {
    if (size == capacity) growArray();
    size++;
    items[size] = key;
    heapifyUp(size);
}
void heap<T>::heapifyUp(int cIndex) {
    if (cIndex > _____)
        if (items[cIndex] ___ items[parent(cIndex)]) {
            swap(__________, __________);
            heapifyUp(__________);
        }
}

(min)Heap: removeMin

4 5 6 15 9 7 20 16 25 14 12 11 4 5 6 15 9 7 20 16 25 14 12 11

Code:

T heap<T>::removeMin() {
    T minVal = items[1];
    items[1] = items[size];
    size--;
    heapifyDown(1);
    return minVal;
}
void heap<T>::heapifyDown(int cIndex) {
    if (hasAChild(cIndex)) {
        minChildIndex = minChild(cIndex);
        if (items[cIndex] ___ items[minChildIndex]) {
            swap(__________, __________);
            ___________________________
        }
    }
}

What have we done?

(min)Heap: buildHeap

B U I L D H E A P N O W W B U I L D H E A P N O

(min)Heap: buildHeap 3 alternatives

B U I L D H E A P N O W B U I L D H E A P N O W

1. Sort the array:

2.

void heap<T>::buildHeap() {
    for (int i=2; i<=size; i++)
        heapifyUp(i);
}

3.

void heap<T>::buildHeap() {
    for (int i=parent(size); i>0; i--)
        heapifyDown(i);
}

buildHeap Explorer

(min)Heap: buildHeap

A B E L D H I U P N O W A B E L D H I U P N O W

Proof of solution to the recurrence:

Thm: buildHeap on an array of size \(n\)
runs in time ________.

Time is proportional to the sum of the
heights of all the nodes. Call it \(S(h)\).

\(S(h) =\)

\(S(0) =\)

Soln \(S(h) =\)

But running times are reported in terms of \(n\), the number of nodes…

(min)Heap: heapSort

A B E L D H I U P N O W A B E L D H I U P N O W

1


2


3

Running time?

Why do we need another sorting algorithm?

heapSort Explorer