1. using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsertHeap
{
class Heap
{
private int max_size;
private int size;
private string[] h;
public Heap(int m)
{
size = 0;
max_size = m+1;
h = new string[max_size];
}
public void insertItem(string item) //max heap
{
size++;
h[size] = item;
int current = size;
int parent = current / 2;
while (parent > 0)
{
if (string.Compare(h[parent], h[current]) < 0) //parent is smaller than
current
{
string temp = h[current];
h[current] = h[parent];
h[parent] = temp;
}
parent = parent / 2;
current = current / 2;
}
}
public void Extract_Max()
{
if (size < 1)
{
Console.WriteLine("Error Message");
}
2. int parent = 1; // start with root at index 1
string max = h[parent]; // extract max, the root is the biggest
h[parent] = h[size]; //swap
h[size] = max; //store the extracted max to the last position of array
size--; //decrease size by 1
int leftChild = 2 * parent; //left child
while (leftChild < size ) //if left child is less than size
{
int rightChild = leftChild + 1; //if right child exist
if (rightChild <= size)
{
if (string.Compare(h[leftChild], h[rightChild]) <= 0) // left child
is smaller than right child
{
string temp = h[rightChild];
h[rightChild] = h[parent];
h[parent] = temp;
parent = rightChild; //replace the rightchild with parent node
int a = 2 * parent;
leftChild = a;
}
else
{
string temp = h[leftChild];
h[leftChild] = h[parent];
h[parent] = temp;
parent = leftChild; //replace the leftchild with parent node
int a = 2 * parent;
leftChild = a;
}
}
else if (leftChild <= size && rightChild > size)
{
if (string.Compare(h[parent], h[leftChild]) <= 0)
{
string t = h[leftChild];
h[leftChild] = h[parent];
h[parent] = t;
parent = leftChild; //replace the leftchild with parent node
int a = 2 * parent;
leftChild = a;
}
}