Question: package timedlab; import java.util.ArrayList; public class Heap { // Your task is to implement a heap using an ArrayList // by completing the specified methods

package timedlab;

import java.util.ArrayList;

public class Heapextends Comparable> {

// Your task is to implement a heap using an ArrayList

// by completing the specified methods

// This is the underlying array

// refer to the Chapter 6 slides if you forget

// It's actually pretty easy if you follow the slides

// Don't overthink it.

private ArrayList heap;

private int size;

public Heap(){

this.heap = new ArrayList();

this.size = 0;

}

// Problem Heap 1 10 pt

// write a method that finds the index of an item's left child.

// The parameter parent in this method is the index of the parent element

// The left child's index is twice the parent's plus 1

private int leftIndex(int parent) {

int leftIndex = -1;

//complete this

return leftIndex;

}

// Problem Heap 2 10 pt

// write a method that finds the index of an item's right child.

// The parameter parent in this method is the index of the parent element

// The right child's index is twice the parent's plus 2

private int rightIndex(int parent) {

int rightIndex = -1;

//complete this

return rightIndex;

}

// Problem Heap 3 10 pt

// write a method that finds the index of an item's parent.

// The parameter child in this method is the index of the child element

// The parent's index is the child's -1 divided by two

private int parentIndex(int child) {

int parentIndex = -1;

//complete this

return parentIndex;

}

// Problem Heap 4 20 points

// Write a method that adds an item to the heap.

// To add an item to the heap, add it to the first empty spot in the arrayList

// Then while the item is smaller than it's parent, swap it with it's parent

// Remember, there are no gaps between items in the array

// You will need to use compareTo

// You do not need to worry about resizing the heap, since the ArrayList does that for you

public void add(E item) {

size++;

}

// use this main to test

public static void main(String[] args) {

}

}

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!