Question

In: Computer Science

This problem requires you to use a heap to store items, but instead of using a key of an item to determine where to store the item in the heap

This problem requires you to use a heap to store items, but instead of using a key of an item to determine where to store the item in the heap, you need to assign a priority (key) to each item that will determine where it is inserted in the heap 


7a) Show how to assign priorities to items to implement a first-in, first-out queue with a heap. 

7b) Show how to assign priorities to items to implement a first-in, last-out stack with a heap.

Solutions

Expert Solution

Solution to part (a) with java code :

The standard approach is to use an array (or an ArrayList), starting at position 1 (instead of 0), where each item in the array corresponds to one node in the heap:

  • The root of the heap is always in array[1].
  • Its left child is in array[2].
  • Its right child is in array[3].
  • In general, if a node is in array[k], then its left child is in array[k*2], and its right child is in array[k*2 + 1].
  • If a node is in array[k], then its parent is in array[k/2] (using integer division, so that if k is odd, then the result is truncated; e.g., 3/2 = 1).

Note that the heap's "shape" property guarantees that there are never any "holes" in the array.

The operations that create an empty heap and return the size of the heap are quite straightforward; below we discuss the insert and removeMax operations.

Insert:

When a new value is inserted into a priority queue, we need to:

  • Add the value so that the heap still has the order and shape properties, and
  • Do it efficiently!

The way to achieve these goals is as follows:

  1. Add the new value at the end of the array; that corresponds to adding it as a new rightmost leaf in the tree (or, if the tree was a complete binary tree, i.e., all leaves were at the same depth d, then that corresponds to adding a new leaf at depth d+1).
  2. Step 1 above ensures that the heap still has the shape property; however, it may not have the orderproperty. We can check that by comparing the new value to the value in its parent. If the parent is smaller, we swap the values, and we continue this check-and-swap procedure up the tree until we find that the order property holds, or we get to the root.

RemoveMax:

Because heaps have the order property, the largest value is always at the root. Therefore, the removeMaxoperation will always remove and return the root value; the question then is how to replace the root node so that the heap still has the order and shape properties.

The answer is to use the following algorithm:

  1. Replace the value in the root with the value at the end of the array (which corresponds to the heap's rightmost leaf at depth d). Remove that leaf from the tree.
  2. Now work your way down the tree, swapping values to restore the order property: each time, if the value in the current node is less than one of its children, then swap its value with the larger child (that ensures that the new root value is larger than both of its children).

Java code:

package Question1_1;

public class PriorityQueueUsingHeap> {
T[] arr;
int N;

public static void main(String[] args) {
PriorityQueueUsingHeap pq = new PriorityQueueUsingHeap();
pq.insert(3);
System.out.println(pq.toString());
pq.insert(5);
System.out.println(pq.toString());
pq.insert(2);
System.out.println(pq.toString());
pq.insert(-1);
System.out.println(pq.toString());
pq.insert(9);
System.out.println(pq.toString());
pq.insert(4);
System.out.println(pq.toString());

pq.delMax();
System.out.println(pq.toString());
pq.delMax();
System.out.println(pq.toString());
pq.delMax();
System.out.println(pq.toString());
pq.delMax();
System.out.println(pq.toString());
pq.delMax();
System.out.println(pq.toString());
}

public PriorityQueueUsingHeap(){
arr = (T[]) new Comparable[2];
N = 0;
}

public void insert(T t){
if (N == arr.length - 1) resize(2*N + 1);
arr[++N] = t;
swim(N);
}

public T delMax(){
if (isEmpty()) return null;
T t= arr[1];
exch(1,N--);
arr[N+1] = null;
sink(1);

//resize this array
if (N == (arr.length -1)/4) resize((arr.length-1) / 2 + 1);
return t;
}
//helper methods
public String toString(){
StringBuffer sb = new StringBuffer();
for(int i = 1; i <= N; i ++)
sb.append(arr[i].toString()+" ");
return sb.toString();
}

private boolean isEmpty(){
return N == 0;
}
private void resize(int capacity){
T[] copy = (T[]) new Comparable[capacity];
for(int i = 1; i <= N; i ++ )
copy[i] = arr[i];
arr = copy;
}

private void swim(int k){
while(k > 1 && less(k/2, k)){
exch(k/2,k);
k = k/2;
}
}

private void sink(int k){
while (2*k < N){
int j = 2 * k;
if(j < N && less(j, j +1)) j = j + 1;
if(less(j, k)) break;
exch(k,j);
k = j;
}
}

private boolean less(int i, int j){
if (arr[i].compareTo(arr[j]) < 0)
return true;
return false;
}

private void exch(int i, int j){
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}


Related Solutions

This problem requires you to use a heap to store items, but instead of using a...
This problem requires you to use a heap to store items, but instead of using a key of an item to determine where to store the item in the heap, you need to assign a priority (key) to each item that will determine where it is inserted in the heap a) Show how to assign priorities to items to implement a first-in, first-out queue with a heap. b) Show how to assign priorities to items to implement a first-in, last-out...
A store accidentally priced item at $20 instead of $30 and honored the mispricing. where should the store attribute the $10 difference?
A store accidentally priced item at $20 instead of $30 and honored the mispricing. where should the store attribute the $10 difference?
1.Instead of Build-Max-Heap, we could use Heap-Insert-Max to build a tree with heap property. Write a...
1.Instead of Build-Max-Heap, we could use Heap-Insert-Max to build a tree with heap property. Write a pseudocode for that procedure, also evaluate it’s time complexity. 2. How Insertion sort works on the following array [16, 12, 3, 27, 9, 4, 5, 7]]
You are required to use only C for this problem. To begin, instead of using two...
You are required to use only C for this problem. To begin, instead of using two different variables for this problem, you are going to define a structure with two members; one representing the feet and the other one representing the inches. We will also use three functions; one to initialize a structure, one to check the validity of its values, and the last one to print them out. First, define your structure. Next, declare a structure of this type...
Determine the labor costs required to manufacture the 100th item if the first item requires 50...
Determine the labor costs required to manufacture the 100th item if the first item requires 50 days to produce and the learning curve is 82%. The manufacturing process requires two 9-hour shifts working each day, with 8 employees per shift. The employees are paid $17.50 per hour.
Question: For each of the following items, determine whether the item would be:
Question: For each of the following items, determine whether the item would be:a. added to the bank balanceb. subtracted from the bank balancec. added to the book balanced. subtracted from the book balance11. Interest revenue earned12. NSF check13. Deposit in transit14. Service charge15. Outstanding check 
In C++ Use vectors instead of linked lists Create a Hash table program using H(key) =...
In C++ Use vectors instead of linked lists Create a Hash table program using H(key) = key%tablesize with Chaining and Linear probing for a text file that has a list of 50 numbers Ask the user to enter the file name, what the table size is, and which of the two options they want to use between chaining and linear probing
Consider the following items in the Knapsack Problem: Item                weight             value &nbsp
Consider the following items in the Knapsack Problem: Item                weight             value            Knapsack capacity W = 9. 1                      3                   $6 2 4 $12 3                      2                  $10 4                      5                  $20 Determine the maximum value in the knapsack if we allow repetitions; i.e., if there are an unlimited number of each item so that more than one such item can be chosen. Find the missing value in the following linear array. P(w) is the maximum profit obtainable for a knapsack of capacity w. w-->             0       1      2       3       4       5       6       7       8       9 P(w):    0 0 10 10     20     20     30    30 40 ?   P(9)...
Use the Heap class provided to implement a sort routine in a Main class where the...
Use the Heap class provided to implement a sort routine in a Main class where the user enters a series of values, each value is then pushed onto a heap, then the values are printed out in ascending order. public class Heap { public static final int SIZE = 1025; public Heap() { elt = new Element[SIZE]; lastLoc = 0; } public void push(String k, Object o) { if (!fullCheck()) { lastLoc++; elt[lastLoc] = new Element(k,o); int loc = lastLoc;...
Answer the same problem as the if statement assignment but use the case statement instead. You...
Answer the same problem as the if statement assignment but use the case statement instead. You are working for a company that offers driver licence training and you have been asked to write a script that asks your clients how old they are. If he/she is 16 years old display the message "Please visit our company to take the test!" If he/she is 15 years old display the message "Please take the training with us to learn how to drive!"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT