Computer Science Notes

Notes From CS Undergrad Courses FSU

This project is maintained by awa03

Priority Queue

Applications of Priority Queues

Implementation

Partially ordered Trees

Binary Heaps

Vector Representation

Basic Heap Operations : Insert (cx)

void insert(const Comparable& x)
{
	if(currSize == array.size()-1){
		array.resize(array.size() * 2)
	}
	int hole = ++currSize;
	Comparable copy = x;
	array[0] = move(copy);
	for(; x < array[hole/2]; hole /= 2){
		array[hole]	= move(array[hole / 2]);
	}
	array[hole] = move(array[0]);
}

Delete Min

void deleteMin(){
	if(isEmpty())
		throw UnderflowException{};
	array[1] = move( array [currSize--]);
	percolateDown(1);
}

percolateDown(int hole){
	int child;
	T tmp = move(array [hole] );
	for(; hole * 2 <= currSize; hole = child){
		child = hole * 2;
		if(child != currSize && array[child+1] < array[child]){
			++child;
		}
		if(array[child] < tmp)
			array[hole] = move(array[child]);
		else
			break;
	}
	array[hole] = move(tmp);
}