patternjavaMinor
Max heap in Java
Viewed 0 times
javamaxheap
Problem
I'm just looking for some feedback on my implementation of a maxheap mostly relating to style. I'm trying to create good habits as I learn to program.
Note: for the sort method I was given the precondition that the passed in array never has empty/null elements and that it must be sorted in place.
Private constructor that is used by the
Public default no-arg constructor that initializes size to 0 and the backing array to a default capacity.
Public copy constructor that takes in another
a new
Adds an element to this
Note: for the sort method I was given the precondition that the passed in array never has empty/null elements and that it must be sorted in place.
public class Heap12> implements PQueue{
private E[] heap; // Backend data storage array
private int size; // # elements in the heapPrivate constructor that is used by the
sort() method to heapify an array of objects type E. Size is initialized to 0 so that the objects in the array can be sorted in place by calling the add(E e) method.@param E[] e - the array to be heapified@SuppressWarnings("unchecked")
private Heap12(E[] e){
this.heap = e; // Set heap array to passed in array
this.size = 0; // Size HAS to be 0 initially
}Public default no-arg constructor that initializes size to 0 and the backing array to a default capacity.
@SuppressWarnings("unchecked")
public Heap12(){
this.size = 0; // Default values
this.heap = (E[]) new Comparable[5];
}Public copy constructor that takes in another
Heap12 object. It createsa new
Heap12 object that is a deep copy of the passed in object. The underlying objects of the backing array are shared, but each Heap12 has its own instance variables.@param Heap12 o - the Heap12 object to be copied@SuppressWarnings("unchecked")
public Heap12(Heap12 o){
this.heap = (E[]) new Comparable[o.heap.length];
this.size = o.size; // Copy size
for(int i = 0; i < o.size(); i++){ // Copy each element
this.heap[i] = o.heap[i]; // reference
}
}Adds an element to this
Heap12 object. Does not accept null elements, will throw a NullPointerException. If the Heap12 is at maximum capacity, the capSolution
One thing that I think need to be fixed is:
You need to copy it, otherwise the caller has reference to your array to corrupt it.
private Heap12(E[] e){
this.heap = e; // Set heap array to passed in array
this.size = 0; // Size HAS to be 0 initially
}You need to copy it, otherwise the caller has reference to your array to corrupt it.
Code Snippets
private Heap12(E[] e){
this.heap = e; // Set heap array to passed in array
this.size = 0; // Size HAS to be 0 initially
}Context
StackExchange Code Review Q#29089, answer score: 3
Revisions (0)
No revisions yet.