#embody <malloc.h>
#embody <stdio.h>
struct
Heap {
int
* arr;
int
dimension;
int
capability;
};
typedef
struct
Heap heap;
heap* createHeap(
int
capability,
int
* nums);
void
insertHelper(heap* h,
int
index);
void
maxHeapify(heap* h,
int
index);
int
extractMax(heap* h);
void
insert(heap* h,
int
knowledge);
heap* createHeap(
int
capability,
int
* nums)
{
heap* h = (heap*)
malloc
(
sizeof
(heap));
if
(h == NULL) {
printf
(
"Reminiscence error"
);
return
NULL;
}
h->dimension = 0;
h->capability = capability;
h->arr = (
int
*)
malloc
(capability *
sizeof
(
int
));
if
(h->arr == NULL) {
printf
(
"Reminiscence error"
);
return
NULL;
}
int
i;
for
(i = 0; i < capability; i++) {
h->arr[i] = nums[i];
}
h->dimension = i;
i = (h->dimension - 2) / 2;
whereas
(i >= 0) {
maxHeapify(h, i);
i--;
}
return
h;
}
void
insertHelper(heap* h,
int
index)
{
int
father or mother = (index - 1) / 2;
if
(h->arr[parent] < h->arr[index]) {
int
temp = h->arr[parent];
h->arr[parent] = h->arr[index];
h->arr[index] = temp;
insertHelper(h, father or mother);
}
}
void
maxHeapify(heap* h,
int
index)
{
int
left = index * 2 + 1;
int
proper = index * 2 + 2;
int
max = index;
if
(left >= h->dimension || left < 0)
left = -1;
if
(proper >= h->dimension || proper < 0)
proper = -1;
if
(left != -1 && h->arr[left] > h->arr[max])
max = left;
if
(proper != -1 && h->arr[right] > h->arr[max])
max = proper;
if
(max != index) {
int
temp = h->arr[max];
h->arr[max] = h->arr[index];
h->arr[index] = temp;
maxHeapify(h, max);
}
}
int
extractMax(heap* h)
{
int
deleteItem;
if
(h->dimension == 0) {
printf
(
"nHeap id empty."
);
return
-999;
}
deleteItem = h->arr[0];
h->arr[0] = h->arr[h->size - 1];
h->size--;
maxHeapify(h, 0);
return
deleteItem;
}
void
insert(heap* h,
int
knowledge)
{
if
(h->dimension < h->capability) {
h->arr[h->size] = knowledge;
insertHelper(h, h->dimension);
h->dimension++;
}
}
void
printHeap(heap* h)
{
for
(
int
i = 0; i < h->dimension; i++) {
printf
(
"%d "
, h->arr[i]);
}
printf
(
"n"
);
}
void
predominant()
{
int
arr[9] = {1,2,3,4,5,6,7,8,9};
heap* hp = createHeap(9, arr);
printHeap(hp);
extractMax(hp);
printHeap(hp);
}