CPSC 221

Priority Queues

Today

Announcements

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


Today:

  • Secret mystery ADT
  • Basic implementations of secret mystery ADT
  • A new kind of tree

Secret Mystery ADT

First, speculate on what type of data you can put into it!


YES          

NO           

Secret Mystery ADT






ADT: ________________

insert

remove

getSize

Priority Queue ADT

insert removeMin implementation unsorted sorted

Priority Queue: another implementation option

Tell me everything you can about this structure:

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

Describe its implementation…

(min)Heap: implementation

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

(min)Heap: insert

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

Code:

void heap<T>::insert(const T & key) {
    if (size == capacity) growArray();
    size++;
    items[size] = key;
    heapifyUp(size);
}

growArray()

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

(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(__________, __________);
            ___________________________
        }
    }
}

Heap Explorer

What have we done?