Question: [FIX ERRORS} [JAVA] import java.util.Comparator; public class Heap implements Cloneable { private java.util.ArrayList list = new java.util.ArrayList (); public Heap(){} public Heap(E[] objects) { for

[FIX ERRORS} [JAVA]

import java.util.Comparator;

public class Heapimplements Cloneable {

private java.util.ArrayList list = new java.util.ArrayList();

public Heap(){}

public Heap(E[] objects) {

for (int i = 0; i< objects.length; i++)

add(objects[i]);

}

public void add(E list2) {

list.add(list2);

int currentIndex = list.size() - 1;

while (currentIndex > 0 ) {

int parentIndex = (currentIndex - 1) / 2;

if (list.get(currentIndex).compareTo(list.get(parentIndex) > 0) {

E temp = list.get(currentIndex);

list.set(currentIndex, list.get(parentIndex));

list.set(parentIndex, temp);

}

else

break;

currentIndex = parentIndex;

}

}

public E remove() {

if(list.size() == 0) return null;

E removedObject = list.get(0);

list.set(0, list.get(list.size() - 1));

list.remove(list.size() - 1);

int currentIndex = 0;

while (currentIndex < list.size()) {

int leftChildIndex = 2 * currentIndex + 1;

int rightChildIndex = 2 * currentIndex + 2;

if (leftChildIndex >= list.size()) break;

int maxIndex = leftChildIndex;

if(rightChildIndex < list.size()){

if(list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0 ) {

maxIndex = rightChildIndex;

}

}

if(list.get(currentIndex).compareTo( list.get(maxIndex)) < 0 ) {

list.get(maxIndex)) < 0 ) {

E temp = list.get(maxIndex);

list.set(maxIndex, list.get(currentIndex));

list.set(currentIndex, temp);

currentIndex = maxIndex;

}

else break;

}

return removedObject;

}

public int getSize() {

return list.size();

}

}

////////////////////////////////////////////

public class HeapSort{

private static final int Comparator = 0;

private static int E;

public static void heapSort (E[] list)

{

Heap heap = new Heap();

for (int i = 0; i< list.length; i++)

heap.add(list[i]);

for (int i = list.length - 1; i >= 0 ; i--)

list[i] = heap.remove()

}

public static void heapSort(Integer[] list, int comparator)

{

Heapheap= new Heap();

for (int i = 0; i < list.length; i++)

heap.add((Comparable) list[i]);

for (int i = list.length - 1; i >= 0; i--)

list[i] = (Integer) heap.remove();

}

public static void main(String[] args) {

Integer[] list = {2,3,2,5,6,1,-2,3,14,12);

System.out.println("Comparator: ");

heapSort(list);

for (int i = 0; i < list.length; i++)

System.out.print(list[i] + " " );

System.out.println();

System.out.println("Comparable: ");

heapSort(list,Comparator);

for (int i = 0; i < list.length; i++)

System.out.print(list[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!