using
System;
class
KaryHeap
{
static
void
restoreDown(
int
[] arr,
int
len,
int
index,
int
k)
{
int
[] child =
new
int
[k + 1];
while
(
true
)
{
for
(
int
i = 1; i <= k; i++)
child[i] = (k * index + i) < len ? (k * index + i) : -1;
int
maxChild = -1, maxChildIndex = 0;
for
(
int
i = 1; i <= k; i++)
{
if
(child[i] != -1 && arr[child[i]] > maxChild)
{
maxChildIndex = child[i];
maxChild = arr[child[i]];
}
}
if
(maxChild == -1)
break
;
if
(arr[index] < arr[maxChildIndex])
swap(
ref
arr[index],
ref
arr[maxChildIndex]);
index = maxChildIndex;
}
}
static
void
restoreUp(
int
[] arr,
int
index,
int
k)
{
int
parent = (index - 1) / k;
while
(parent >= 0)
{
if
(arr[index] > arr[parent])
{
swap(
ref
arr[index],
ref
arr[parent]);
index = parent;
parent = (index - 1) / k;
}
else
break
;
}
}
static
void
buildHeap(
int
[] arr,
int
n,
int
k)
{
for
(
int
i = (n - 1) / k; i >= 0; i--)
restoreDown(arr, n, i, k);
}
static
void
insert(
int
[] arr,
ref
int
n,
int
k,
int
elem)
{
arr[n] = elem;
n++;
restoreUp(arr, n - 1, k);
}
static
int
extractMax(
int
[] arr,
ref
int
n,
int
k)
{
int
max = arr[0];
arr[0] = arr[n - 1];
n--;
restoreDown(arr, n, 0, k);
return
max;
}
static
void
Main(
string
[] args)
{
const
int
capacity = 100;
int
[] arr =
new
int
[capacity] { 4, 5, 6, 7, 8, 9, 10 };
int
n = 7;
int
k = 3;
buildHeap(arr, n, k);
Console.WriteLine(
"Built Heap : "
);
for
(
int
i = 0; i < n; i++)
Console.Write(
"{0} "
, arr[i]);
int
element = 3;
insert(arr,
ref
n, k, element);
Console.WriteLine(
"\n\nHeap after insertion of {0}: "
, element);
for
(
int
i = 0; i < n; i++)
Console.Write(
"{0} "
, arr[i]);
Console.WriteLine(
"\n\nExtracted max is {0}"
, extractMax(arr,
ref
n, k));
Console.WriteLine(
"\n\nHeap after extract max: "
);
for
(
int
i = 0; i < n; i++)
Console.Write(
"{0} "
, arr[i]);
Console.ReadLine();
}
static
void
swap(
ref
int
a,
ref
int
b)
{
int
temp = a;
a = b;
b = temp;
}
}