Question: Convert the given Java source code for MaxBinaryHeap and HeapSort to a Min - Binary Heap and Decreasing Heap Sort by changing the direction of

Convert the given Java source code for MaxBinaryHeap and HeapSort to a Min-Binary Heap and Decreasing Heap Sort by changing the direction of two comparing operators in the percolateDown method (replace > by <). Execute the test case available in the main method of the given java file:
public static void main(String[] args){
Comparable[] array = new Comparable[]{-1,5,6,2,3,1,8,4,0};
heapSort(array);
for(int i =1; i < array.length;i++)
System.out.println(array[i]);
}
Starter Code:
public class BinaryHeap>{
private Comparable[] data;
private int size =0;
public BinaryHeap(int capacity){
data = new Comparable[capacity];
}
public BinaryHeap(Comparable[] data){
this.data = data;
size = data.length -1;
for(int i = size/2; i >=1;i--)
percolateDown(i);
}
public int size(){
return size;
}
private void percolateDown(int root){//heapify
int leftChild = root *2;
int rightChild = leftChild +1;
int max; //max of left,, right, and parent nodes.
//comparing parent with left child
if(leftChild <= size && data[leftChild].compareTo(data[root])>0)
max = leftChild;
else
max = root;
//comparing the max with the right child
if (rightChild <= size && data[rightChild].compareTo(data[max])>0)
max = rightChild;
if(max != root){//if not the base case!
Comparable temp = data[root];//swapping max w/ root
data[root]= data[max];
data[max]= temp;
percolateDown(max);
}
}
public Comparable extractMax(){
if(size ==0)
throw new IllegalStateException();
Comparable rv = data[1];
data[1]= data[size];//swap root w/ last leaf
data[size]= rv;
size--;
percolateDown(1);//heapify the root
return rv;
}
public static BinaryHeap buildHeap(Comparable[] values){
return new BinaryHeap(values);
}
public static void heapSort(Comparable[] values){
BinaryHeap heap = buildHeap(values);
for(int i =0; i < values.length -1;i++)
heap.extractMax();
}
public static void main(String[] args){
Comparable[] array = new Comparable[]{-1,5,6,2,3,1,8,4,0};
heapSort(array);
for(int i =1; i < array.length;i++)
System.out.println(array[i]);
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!