All pastes #2000681 Raw Edit

heap

public cpp v1 · immutable
#2000681 ·published 2010-11-24 03:57 UTC
rendered paste body
#include<assert.h>#include<stdlib.h>#include<iostream>/**  * Author: Shriphani Palakodety  ***/using namespace std;class Heap{	int maxSize;	int last;	int *heap;	public:		Heap(int maxSize)		{			Heap::maxSize = maxSize;			last = 0;			heap = (int *)malloc(maxSize * sizeof(int));		}				int left(int p)		{			return 2*p + 1;		}		int right(int p)		{			return 2*p + 2;		}		int parent(int p)		{			return (p - 1)/2;		}		void upheap()		{			int child = last -1;			int par = parent(child);			while (child  > 0)			{				if (*(heap + child) > *(heap + par))				{					break;				}				else				{					int temp = heap[child];					heap[child] = heap[par];					heap[par] = temp;					child = par;					par = parent(child);				}			}		}		void insert(int key)		{			assert(last < maxSize);			heap[last] = key;			last++;			upheap();		}		int removeMin()		{			//remove the root			int val = heap[0];			//place last element in the root location			heap[0] = heap[last-1];			last--; //akin to removing the last element			//now apply downheap			int par = 0;			int lchild = left(par);			int rchild = right(par);			while (lchild <= last && rchild <= last)			{				int minChild = lchild;				if (heap[rchild] < heap[lchild])				{					minChild = rchild;				}				if (heap[minChild] < heap[par])				{					//swap is needed					int temp = heap[minChild];					heap[minChild] = heap[par];					heap[par] = temp;					par = minChild;					lchild = left(par);					rchild = right(par);				}				else				{					break;				}			}			return val;		}		void iterate()		{			int i;			for (i = 0; i < last; i++)			{				cout << heap[i] << " ";			}			cout << endl;		}};int main(){	Heap *a = new Heap(7);	(*(a)).insert(2);	(*(a)).insert(1);	//(*a).iterate();	(*a).insert(3);	(*a).insert(4);	(*a).insert(20);	(*a).insert(6);	(*a).insert(5);	(*a).iterate();	cout << (*a).removeMin() << endl;	cout << (*a).removeMin() << endl;	cout << (*a).removeMin() << endl;	cout << (*a).removeMin() << endl;	cout << (*a).removeMin() << endl;	cout << (*a).removeMin() << endl;	cout << (*a).removeMin() << endl;		delete a;	int unsorted[] = { 1, 5, 4, 3, 6, 2, 9, 8, 7, 10, 15, 12, 11 };	Heap *b = new Heap(13);	int i;	for (i = 0; i < 13; i++)		(*b).insert(unsorted[i]);	for (i = 0; i < 13; i++)	{		int a = (*b).removeMin();		unsorted[i] = a;		cout << a << endl;	}	for (i = 0; i < 13; i++)	{		cout << unsorted[i] << ", ";	}}