Skip to content

Instantly share code, notes, and snippets.

@georgismitev
Created November 22, 2015 13:47
Show Gist options
  • Save georgismitev/311b20db37106020a37d to your computer and use it in GitHub Desktop.
Save georgismitev/311b20db37106020a37d to your computer and use it in GitHub Desktop.
using System;
public class Program
{
public class Heap
{
int[] heap;
int elements;
//will have children nodes arr[2*i + 1] and arr[2*i + 2],
//and parent node arr[(i-1)/2].
public void Swap(ref int a, ref int b)
{
int temp = b;
b = a;
a = temp;
}
public void Insert(int val)
{
heap[elements] = val;
int i=elements;
while (heap[(i-1)/2] < heap[i])
{
Swap(ref heap[(i-1)/2], ref heap[i]);
i = (i-1) /2;
}
elements++;
}
public void DeleteRoot()
{
int i = 0;
Swap(ref heap[i], ref heap[elements-1]);
elements--;
while (2*i + 2 < elements)
{
int leftChild = 2*i + 1;
int rightChild = 2*i + 2;
if (heap[leftChild] > heap[rightChild])
{
Swap(ref heap[i], ref heap[leftChild]);
i = leftChild;
}
else
{
Swap(ref heap[i], ref heap[rightChild]);
i = rightChild;
}
}
}
public void Display()
{
int levels = (int)Math.Log(elements, 2);
int currentLevel = 0;
int j=1;
for (int i=0;i<elements;i++)
{
if (i == j)
{
j=j*2+1;
Console.WriteLine();
currentLevel++;
}
Console.Write("{0, -5}", heap[i]);
}
}
public Heap(int size)
{
heap = new int[size];
elements = 0;
}
}
public static void Main()
{
var x = new Random();
int size = x.Next(10)+1;
var h = new Heap(size);
for (int i=0;i<size;i++)
{
h.Insert(x.Next(50)+1);
}
h.Display();
Console.WriteLine();
Console.WriteLine();
h.DeleteRoot();
h.Display();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment