Heap

Garbage

children elements are smaller/bigger than parent

Types of Heaps

  • Min Heap : Highest priority items assigned the lowest value

  • Max Heap : Highest priority items assigned the highest value

Applications of Heap

  • Used to implement HeapSort

  • Used to implement PriorityQueue

Formulae's

  • left of element : (2*i+1)

  • right of element : (2*i+2)

  • parent of element : (i-1)/2

Binary Heap Implementation (Array)

import java.util.*;
import java.io.*;
import java.lang.*;

class Main {

    public static class MinHeap {
        int arr[];
        int size;
        int capacity;

        MinHeap(int c) {
            size = 0;
            capacity = c;
            arr = new int[c];
        }

        int left(int i) {
            return (2 * i + 1);
        }

        int right(int i) {
            return (2 * i + 2);
        }

        int parent(int i) {
            return (i - 1) / 2;
        }
    }

    public static void main(String args[]) {
        MinHeap h = new MinHeap(11);

    }

}

Binary Heap Insert (Array) : MinHeap

Binary Heap (Heapify and Extract) : MinHeap

Extract operation is super important

Binary Heap (Decrease Key | Delete)

Binary Heap ( Build Heap ) IMPORTANT

Heap Sort

Priority Queue (Min Heap Edition)

Priority Queue (Max Heap Edition)

K-Sorted Array

Buy Maximum Items with the given sum

Kth Largest Element

K Closet Element

Merge K Sorted Arrays

Median of Stream

Last updated