So I made a min heap of Binary trees. To test it I create a bunch of nodes with 2 different values.
Say
struct node
{
int frequency;
int data;
}
Say frequency is what the heap primarily sorts by, but if the nodes frequency is the same, it is to then sort by the nodes data.
When I make a bunch of node's, and load up the heap, and pop and print them im getting ( Size, is how many nodes are in the tree, and min is the minimum data held by each tree)
Data Freq Size Min
10 1 1 10
84 1 1 84
115 1 1 115
66 1 1 66
114 1 1 114
100 1 1 100
121 2 1 121
111 2 1 111
104 3 1 104
97 3 1 97
101 5 1 101
108 5 1 108
83 6 1 83
32 9 1 32
If you didnt notice, the third entry is wrong, and consequently, the heap is wrong.
My bug lies somewhere in the minheap upheap downheap, remove or insert.
Ive been trying for days, my brain just can't handle it, to much other fun stuff to do, like sim city. ( not really, i have to finish this)
Here is my heap
class MinHeap
{
public:
int length;
MinHeap(int mVal );
~MinHeap();
int size(); // returns N, the size of the heap
void insert(node* e);
node* remove();
void printheap();
private:
node **a; // Array of pointers
int MaxSize;
int N; // current size of heap
int itemMin;
void upheap(int k);
void downheap(int k);
};
MinHeap::MinHeap(int mVal)
{
a = new node*[mVal+1](); // a** is an array of pointers;
N=0; // Sets heap size to zero
a[0]= new node();
length = mVal+1;
MaxSize = mVal;
itemMin = -32767; // Minimum Heap
a[0]->frequency= itemMin ;
}
MinHeap::~MinHeap()
{ delete [] a;}
void MinHeap::upheap(int k)
{
node *e = a[k] ;
while( e->frequency < a[k/2]->frequency )
{
a[k] = a[k/2] ; //move parent down
k = k/2 ;
}
while(e->frequency == a[k/2]->frequency && e->minkey < a[k/2]->minkey)
{
a[k] = a[k/2] ; //move parent down
k = k/2 ;
}
a[k] = e ;
}
void MinHeap::downheap(int k)
{
int j = 2 * k ;
node *e = a[k] ;
while (j <= N) {
if ((j < N) && (a[j+1]->frequency < a[j]->frequency)) j++ ;
if((j<N) && (a[j+1]->frequency == a[j]->frequency) && (a[j+1]->minkey > a[j]->minkey ))j++;
if (( e->frequency <= a[j]->frequency) ) break;
a[j/2] = a[j]; // move child up
j *= 2; // move child down a level
}
a[j/2] = e;
}
void MinHeap::insert(node* e)
{
a[++N] = e ;
upheap(N) ;
}
node* MinHeap::remove()
{
node *e = a[1];
a[1] = a[N--]; downheap(1) ;
return &(*e);
}
I should mention I am required to make my own STL classes, and the heap is suppose to also choose priority with the minimum value held in a tree if the frequencies are the same, so that is what the minkey pointer is in the code. Just need to figure out why its not in the correct order.
My program is for a huffman coder, here it is: My Files
It has a make file which compiles on ubuntu 64 systems. Use redirection for input.
The heap from above comes from
echo " Sally Sold Sea Shells By The Sea Shore" > input
./huff < input