I am writing a program to execute a heap sort. When I try to execute the removeMin function, and a downheap, it seems that I am always getting incorrect output.
For example if I input 10 integers in this order:
3, 6, 8, 3, 89, 35, 7, 9, 1, 4
I expect
1, 3, 3, 4, 6, 7, 8, 9, 35, 89
But I get:
1, 3, 3, 4, 6, 7, 8, 9, 35, 35
Here is my code heap code:
public class heapsort {
private Integer[] myHeap;
private int size;
private int maxSize;
public heapsort (int x){
myHeap = new Integer[x+1];
maxSize=x;
size=0;
}
public void min(){
if (isEmpty())
System.out.print("Is empty");
else
System.out.println(myHeap[0]);
}
public boolean isEmpty(){
return (size==0);
}
public int size(){
return size;
}
public void insert(int x){
if (size==maxSize)
System.out.println("Heap is full");
else{
size++;
myHeap[size] = x;
upheap(size);
}
}
public void upheap(int x){
int temp;
if (x>1){
if (myHeap[x]<myHeap[x/2]){
temp = myHeap[x];
myHeap[x]=myHeap[x/2];
myHeap[x/2]=temp;
upheap(x/2);
}
}
}
public void removeMin(){
int temp;
temp = myHeap[1];
myHeap[1]=myHeap[size-1];
size--;
if (size>1){
downheap(1);
}
System.out.println(temp);
}
public void downheap(int x){
int temp;
int temp, minIndex, left=2*x, right=2*x+1;
if (right>=size){
if (left>=size)
return;
else
minIndex=left;
}
else{
if (myHeap[left] <= myHeap[right])
minIndex = left;
else
minIndex = right;
}
if (myHeap[x] > myHeap[minIndex]){
temp = myHeap[minIndex];
myHeap[minIndex]=myHeap[x];
myHeap[x]=temp;
downheap(minIndex);
}
}
Followed by my main program:
public static void main (String[] args){
int i=0;
Scanner input = new Scanner(System.in);
System.out.println("Enter array size: ");
int n = input.nextInt();
heapsort myArray = new heapsort(n);
System.out.println("Please input integers");
for (i=1; i<=n; i++){
myArray.insert(input.nextInt());
}
while (!myArray.isEmpty()){
myArray.removeMin();
}
}
}