Original Post
I'm trying to implement a priority heap at school but it doesn't work when adding more than 289 elements, well actually the adding works but it doesn't work when to dequeue them. This is the situation, I should add X elements to the array and take the time for the process of it, and then I should check how long it will take to dequeue them. like this: I should test the SIZE with sizes 100000, 500000, 1000000, 5000000, all of them works when enqueue only, it crasch when trye to dequeue the items. altough if SIZE is 289 then it works to dequeue. Heap source
timer->start();
for( int i=0; i<SIZE; i++ )
{
heap->enqueue( rand() );
}
float enqueue_time = timer->end();
timer->start();
while( !heap->isEmpty() )
{
heap->dequeue();
};
float dequeue_time = timer->end();
#ifndef CHeap_H
#define CHeap_H
#include "CPriorityQueue.h"
template <class T>
class CHeap : public CPriorityQueue<T> {
int m_iMaxSize; //!< Size of heap. Default 10
int m_iLastItem; //!< Last item index in array
T *m_pHeap; //!< Heap array.
void reheapUp(int index)
{
if ( index == 0 )
return;
int parent = ((index+1) / 2)-1;
if( m_pHeap[parent] > m_pHeap[index] )
return;
T saveItem = m_pHeap[index];
m_pHeap[index] = m_pHeap[parent];
m_pHeap[parent] = saveItem;
reheapUp(parent);
}
void reheapDown(int index)
{
int swap = (2 * (index+1))-1;
if( (m_pHeap[index] > m_pHeap[swap]) && (m_pHeap[index] > m_pHeap[swap+1]) )
return;
if( m_pHeap[swap] < m_pHeap[swap+1] )
swap++;
if( swap > m_iLastItem )
return;
T saveMe = m_pHeap[index];
m_pHeap[index] = m_pHeap[swap];
m_pHeap[swap] = saveMe;
reheapDown(swap);
}
public:
CHeap(int size=10)
{
m_iMaxSize = size;
m_iLastItem = -1;
m_pHeap = new T[m_iMaxSize];
}
void enqueue( T o )
{
m_iLastItem++;
m_pHeap[m_iLastItem] = o ;
if( m_iLastItem > 0 )
{
reheapUp(m_iLastItem);
}
}
T dequeue()
{
if( isEmpty() )
throw QUEUE_EMPTY;
T removeMe = m_pHeap[0];
m_pHeap[0] = m_pHeap[m_iLastItem];
reheapDown(0);
m_iLastItem--;
return removeMe;
}
T peek()
{ return m_pHeap[0]; }
bool isFull()
{ return (m_iLastItem >= m_iMaxSize); }
bool isEmpty()
{ return (m_iLastItem < 0); }
int getSize()
{
return m_iLastItem;
}
void destroyQueue()
{
if( m_pHeap != NULL )
delete m_pHeap;
}
/**
Print queue to standard output.
*/
void printQueue()
{
cout << "----------------" << endl;
for( int i=0; i<m_iLastItem; i++ )
{
cout << "(" << i << ") " << m_pHeap << endl;
}
cout << "----------------" << endl;
}
};
#endif // CHeap_H
[/soucre]
Heap template is using integer in test program CHeap<int> heap;