Hello,
I am attempting to create a program that accomplishes the following:
*I am to develop a heap, that is tree-based(not array)
*The heap should be ascending
*Include the method toss()
-This method will randomly toss a node into the heap and will not maintain the proper heap conditions
*Include restoreHeap() method
- In the application, after calling the toss() method a few times. Utilize restoreHeap() to reposition the tossed nodes into their proper location according to the conditions of a heap
Currently below is what I have, unfortunately, I am only able to make toss and restoreHeap array based. Could someone please provide inline comments on the proper way to change my current methods to tree-based?
Any other inline comments are very appreciated to accomplish this task. I am very understanding of the logic, however, my java syntax is not so great.
Thank you and I look forward to working with you!!
/**
*
*
*
*/
class theNode
{
private int data;
public theNode (int theData)
{
data = theData;
}
public int getit()
{
return data;
}
public void setit(int theData)
{
data = theData;
}
}//end theNode class
/**
*
*
*
*/
public class treeHeap
{
private theNode[] heapArray;
private int treeSize;
private int Elems;
private int index;
/**
*
*
*
*/
public treeHeap(int theSize)
{
treeSize = theSize;
Elems = 0;
heapArray = new theNode[treeSize];
}
/**
*
*
*
*/
public void toss(int tossIt)
{
int data = Elems;
theNode newNode = new theNode(tossIt);
heapArray[Elems] = newNode;
while(data >= 1)
{
heapArray[tossIt++] = data % 2;
data = data / 2;
}
Elems++;
}//end toss()
/**
*
*
*
*/
public void restoreHeap()
{
int parent = (index - 1) / 2;
theNode bottom = heapArray[index];
while(index > 0 && heapArray[parent].getit() < bottom.getit())
{
heapArray[index] = heapArray[parent];
index = parent;
parent = (parent - 1) / 2;
}
heapArray[index] = bottom;
System.out.println();
}
}//end treeHeap Class
/**
*
*
*
*/
class treeHeapApp
{
public static void main(String[] args)
{
treeHeap theTreeHeap = new treeHeap(31);
theTreeHeap.toss(15);
theTreeHeap.toss(87);
theTreeHeap.toss(51);
theTreeHeap.toss(62);
theTreeHeap.toss(8);
theTreeHeap.toss(41);
theTreeHeap.toss(12);
theTreeHeap.toss(66);
theTreeHeap.toss(24);
theTreeHeap.toss(99);
theTreeHeap.restoreHeap();
}
}