Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

=+ Have I included all the elements my readers expect to see?

Answered: 1 week ago