Looking for some simple tips to fix my heapSort. Hopefully it is something simple that I am not comprehending.
I am having a problem with my dumpHeap()
and extractMax()
methods. It seems to put the dumpheap
in order but adds a 0
to my array. It still is technically a heap but bothers me why a 0
appears.
My other question is that my extractMax
will not extract the max numbers in descending order which list the numbers that were extracted.
My outputs read which are wrong:
Original Array : 10 2 8 4 18 20 3 16 5
Max-Heap : 20 18 16 10 8 4 2 3 0 5
Extract Max : 20 5 0 3 2 4 8 10 16
If I could get some tips to where to look/change things around, it would be greatly appreciated.
Thanks!
public class heap {
public int size;
public int [] H;
public int position;
public heap(int size)
{
this.size=size;
H = new int [10];
position = 0;
}
public void createHeap(int [] arrA)
{
if(arrA.length>0)
{
for(int i=0;i<arrA.length;i++)
{
insert(arrA[i]);
}
}
}
public void dumpHeap()
{
for(int i=0;i<H.length;i++)
{
System.out.print(" " + H[i]);
}
System.out.println("");
}
public void insert(int x)
{
if(position==0)
{
H[position]=x;
position = 2;
}else{
H[position++]=x;
exchange();
}
}
public void exchange()
{
int pos = position-1;
while(pos > 0 && H[pos] > H[pos/2])
{
int y = H[pos];
H[pos]=H[pos/2];
H[pos/2] = y;
pos = pos/2;
}
}
public int extractMax()
{
int max = H[0];
H[0]=H[position-1];
H[position-1]= 0;
position--;
extractSort(0);
return max;
}
public void extractSort(int k)
{
int a = H[k];
int maxNum =k;
if(2*k>position && H[maxNum]<H[2*k])
{
maxNum = 2*k;
}
if(2*k+1>position && H[maxNum]<H[2*k+1])
{
maxNum = 2*k+1;
}
if(maxNum!=k)
{
swap(maxNum,k);
extractSort(k);
}
}
public void swap(int a, int b)
{
int temp = H[a];
H[a] = H[b];
H[b] = temp;
}
}
public class heapMain {
public static void main(String args[])
{
int arrA [] = {10,2,8,4,18,20,3,16,5};
System.out.print("Original Array : ");
for(int i=0;i<arrA.length;i++)
{
System.out.print(" " + arrA[i]);
}
heap h = new heap(arrA.length);
System.out.print("\nMax-Heap : ");
h.createHeap(arrA);
h.dumpHeap();
System.out.print("Extract Max :");
for(int i=0;i<arrA.length;i++)
{
System.out.print(" " + h.extractMax());
}
}
}