void SortedList<T, Pred>::swapNodes(typename SortedList<T, Pred>::Node* first, typename SortedList<T, Pred>::Node* second) { // Need to swap 4 sets of pointers. // Note: Always swap adjacent Node pointers before the pointers to the // adjacent Nodes themselves. swap_items(first->Prev->Next, second->Prev->Next); swap_items(first->Prev, second->Prev); swap_items(first->Next->Prev, second->Next->Prev); swap_items(first->Next, second->Next); }
void PriorityQueue<KEY, DATA>::reheapify_with_children(unsigned index) { // item w/ given index may not be in proper heap order; make it so // in time O(log(size())) by moving the item downwards as far as necessary while (true) { // does at least 1 child exist? unsigned child1index = 2*index + 1; unsigned child2index = 2*index + 2; if (child1index >= size()) break; // neither child is in range // invariant: at least one child (child1index) is in range unsigned smallerChildIndex = child1index; if (child2index < size()) // the second child exists; perhaps its key is the smaller of the 2 children if (data[child2index].theKey < data[child1index].theKey) smallerChildIndex = child2index; if (data[smallerChildIndex].theKey < data[index].theKey) { swap_items(index, smallerChildIndex); index = smallerChildIndex; } else break; } }
void PriorityQueue<KEY, DATA>::reheapify_with_parent(unsigned index) { // item w/ given index may not be in proper heap order; make it so // in time O(log(size())) by moving the item upwards as far as necessary while (index > 0) { unsigned parentIndex = (index-1) / 2; if (data[index].theKey < data[parentIndex].theKey) { // out of order; swap swap_items(parentIndex, index); index = parentIndex; } else break; } }
void PriorityQueue<KEY, DATA>::delete_first() { bool aflag; aflag=!empty(); assert(aflag); if (size()==1) { // the queue will now be empty data.resize(0); return; } // swap first item with last item; fry last item (used to be first); // reheapify first item (used to be last) assert(size() > 1); swap_items(0, size()-1); data.resize(size()-1); // our situation: the top item in the heap may be out of heap // order w.r.t. its children reheapify_with_children(0); }