Binary Heap using C#

A Binary Heap is a Binary Tree with following properties.

  1. It’s a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
  2. A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.

How is Binary Heap represented?
A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as an array.

  • The root element will be at Arr[0].
  • Below table shows indexes of other nodes for the ith node, i.e., Arr[i]:
Arr[(i-1)/2] Returns the parent node
Arr[(2*i)+1] Returns the left child node
Arr[(2*i)+2] Returns the right child node

The traversal method use to achieve Array representation is Level Order

Operations on Min Heap:
1) getMini(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).

2) extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Logn) as this operation needs to maintain the heap property (by calling heapify()) after removing root.

3) decreaseKey(): Decreases value of key. The time complexity of this operation is O(Logn). If the decreases key value of a node is greater than the parent of the node, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.

4) insert(): Inserting a new key takes O(Logn) time. We add a new key at the end of the tree. IF new key is greater than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.

5) delete(): Deleting a key also takes O(Logn) time. We replace the key to be deleted with minum infinite by calling decreaseKey(). After decreaseKey(), the minus infinite value must reach root, so we call extractMin() to remove the key.

Below is the implementation of basic heap operations.

// C# program to demonstrate common

// Binary Heap Operations - Min Heap

using System;

// A class for Min Heap

class MinHeap{

// To store array of elements in heap

public int [] heapArray{ get ; set ; }

// max size of the heap

public int capacity{ get ; set ; }

// Current number of elements in the heap

public int current_heap_size{ get ; set ; }

// Constructor

public MinHeap( int n)

{

capacity = n;

heapArray = new int [capacity];

current_heap_size = 0;

}

// Swapping using reference

public static void Swap<T>( ref T lhs, ref T rhs)

{

T temp = lhs;

lhs = rhs;

rhs = temp;

}

// Get the Parent index for the given index

public int Parent( int key)

{

return (key - 1) / 2;

}

// Get the Left Child index for the given index

public int Left( int key)

{

return 2 * key + 1;

}

// Get the Right Child index for the given index

public int Right( int key)

{

return 2 * key + 2;

}

// Inserts a new key

public bool insertKey( int key)

{

if (current_heap_size == capacity)

{

// heap is full

return false ;

}

// First insert the new key at the end

int i = current_heap_size;

heapArray[i] = key;

current_heap_size++;

// Fix the min heap property if it is violated

while (i != 0 && heapArray[i] <

heapArray[Parent(i)])

{

Swap( ref heapArray[i],

ref heapArray[Parent(i)]);

i = Parent(i);

}

return true ;

}

// Decreases value of given key to new_val.

// It is assumed that new_val is smaller

// than heapArray[key].

public void decreaseKey( int key, int new_val)

{

heapArray[key] = new_val;

while (key != 0 && heapArray[key] <

heapArray[Parent(key)])

{

Swap( ref heapArray[key],

ref heapArray[Parent(key)]);

key = Parent(key);

}

}

// Returns the minimum key (key at

// root) from min heap

public int getMin()

{

return heapArray[0];

}

// Method to remove minimum element

// (or root) from min heap

public int extractMin()

{

if (current_heap_size <= 0)

{

return int .MaxValue;

}

if (current_heap_size == 1)

{

current_heap_size--;

return heapArray[0];

}

// Store the minimum value,

// and remove it from heap

int root = heapArray[0];

heapArray[0] = heapArray[current_heap_size - 1];

current_heap_size--;

MinHeapify(0);

return root;

}

// This function deletes key at the

// given index. It first reduced value

// to minus infinite, then calls extractMin()

public void deleteKey( int key)

{

decreaseKey(key, int .MinValue);

extractMin();

}

// A recursive method to heapify a subtree

// with the root at given index

// This method assumes that the subtrees

// are already heapified

public void MinHeapify( int key)

{

int l = Left(key);

int r = Right(key);

int smallest = key;

if (l < current_heap_size &&

heapArray[l] < heapArray[smallest])

{

smallest = l;

}

if (r < current_heap_size &&

heapArray[r] < heapArray[smallest])

{

smallest = r;

}

if (smallest != key)

{

Swap( ref heapArray[key],

ref heapArray[smallest]);

MinHeapify(smallest);

}

}

// Increases value of given key to new_val.

// It is assumed that new_val is greater

// than heapArray[key].

// Heapify from the given key

public void increaseKey( int key, int new_val)

{

heapArray[key] = new_val;

MinHeapify(key);

}

// Changes value on a key

public void changeValueOnAKey( int key, int new_val)

{

if (heapArray[key] == new_val)

{

return ;

}

if (heapArray[key] < new_val)

{

increaseKey(key, new_val);

} else

{

decreaseKey(key, new_val);

}

}

}

static class MinHeapTest{

// Driver code

public static void Main( string [] args)

{

MinHeap h = new MinHeap(11);

h.insertKey(3);

h.insertKey(2);

h.deleteKey(1);

h.insertKey(15);

h.insertKey(5);

h.insertKey(4);

h.insertKey(45);

Console.Write(h.extractMin() + " " );

Console.Write(h.getMin() + " " );

h.decreaseKey(2, 1);

Console.Write(h.getMin());

}

}

Output:

2 4 1