max heap insertion code example

Example 1: max heap java

import java.util.PriorityQueue;

public class MaxHeapWithPriorityQueue {

    public static void main(String args[]) {
        // create priority queue
        PriorityQueue<Integer> prq = new PriorityQueue<>(Comparator.reverseOrder());

        // insert values in the queue
        prq.add(6);
        prq.add(9);
        prq.add(5);
        prq.add(64);
        prq.add(6);

        //print values
        while (!prq.isEmpty()) {
            System.out.print(prq.poll()+" ");
        }
    }

}

Example 2: delete an element from a given position in min heap

1, Delete a node from the array 
       (this creates a "hole" and the tree is no longer "complete")

    2. Replace the deletion node
       with the "fartest right node" on the lowest level
       of the Binary Tree
       (This step makes the tree into a "complete binary tree")

    3. Heapify (fix the heap):

         if ( value in replacement node < its parent node )
            Filter the replacement node UP the binary tree
         else
	    Filter the replacement node DOWN the binary tree

Example 3: min heap insertion

Williams Algorithm: top downwhile not end of array, 	if heap is empty, 		place item at root; 	else, 		place item at bottom of heap; 		while (child > parent) 			swap(parent, child); 	go to next array element; end

Example 4: min heap insertion

Williams Algorithm: top downwhile not end of array, 	if heap is empty, 		place item at root; 	else, 		place item at bottom of heap; 		while (child < parent) 			swap(parent, child); 	go to next array element; end

Tags:

Cpp Example