Question

PLEASE ANSWER ALL IN JAVa how does adding a new element to a heap work? describe...

PLEASE ANSWER ALL IN JAVa


how does adding a new element to a heap work? describe the algorithm in detail

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Insert-2 into a following heap: 3 6 5 Insert a new element to the end of the array: 3 6 5 5 9) (8 -2 1 3 65 9 8 -2 In the general case, after insertion, heap property near the new node is broken:

The heap insertion algorithm in pseudo code:

    Insert a node containing the insertion value
       in the "fartest left location" of the lowest level
       of the Binary Tree

    Filter the inserted node up using this algorithm:

       while (  inserted node's value < value in its parent node )     
       {
          swap the values of the respective node;
       }

JAVA CODE

import java.util.Arrays;

import java.util.NoSuchElementException;

/** Class BinaryHeap **/

public class BinaryHeap {

/** The number of children each node has **/

private static final int d = 2;

private int heapSize;

private int[] heap;

/** Constructor **/

public BinaryHeap(int capacity)

{

heapSize = 0;

heap = new int[capacity + 1];

Arrays.fill(heap, -1);

}

/** Function to check if heap is empty **/

public boolean isEmpty( )

{

return heapSize == 0;

}

/** Check if heap is full **/

public boolean isFull( )

{

return heapSize == heap.length;

}

/** Function to get index parent of i **/

private int parent(int i)

{

return (i - 1)/d;

}

/** Function to insert element */

public void insert(int x)

{

if (isFull( ) )

throw new NoSuchElementException("Overflow Exception");

/** Percolate up **/

heap[heapSize++] = x;

heapifyUp(heapSize - 1);

}

  

/** Function heapifyUp **/

private void heapifyUp(int childInd)

{

int tmp = heap[childInd];

while (childInd > 0 && tmp < heap[parent(childInd)])

{

heap[childInd] = heap[ parent(childInd) ];

childInd = parent(childInd);

}

heap[childInd] = tmp;

}

  

/** Function to print heap **/

public void printHeap()

{

System.out.print("\nHeap = ");

for (int i = 0; i < heapSize; i++)

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

System.out.println();

}

}

Add a comment
Know the answer?
Add Answer to:
PLEASE ANSWER ALL IN JAVa how does adding a new element to a heap work? describe...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT