#include <stdio.h>
#include <stdlib.h>
typedef struct HeapStruct
*pHeap
;
struct HeapStruct
{
int *data
;
int size
;
int capacity
;
};
typedef pHeap MaxHeap
;
typedef pHeap MinHeap
;
#define MAXDATA 1000
#define ERROR -999
MaxHeap
createHeap(int maxSize
) {
MaxHeap heap
= (MaxHeap
)malloc(sizeof(struct HeapStruct
));
heap
->data
= (int *)malloc(++maxSize
*sizeof(int));
heap
->size
= 0;
heap
->capacity
= maxSize
;
heap
->data
[0] = MAXDATA
;
return heap
;
}
bool
isFull(MaxHeap heap
) {
return heap
->capacity
<= heap
->size
;
}
bool
isEmpty(MaxHeap heap
) {
return heap
->size
== 0;
}
bool
insert(MaxHeap heap
, int item
) {
int i
;
if (isFull(heap
)) {
printf("Heap is Full");
return false
;
}
i
= ++heap
->size
;
for (; heap
->data
[i
/ 2] < item
;i
/=2) {
heap
->data
[i
] = heap
->data
[i
/ 2];
}
heap
->data
[i
] = item
;
return true
;
}
int deleteMax(MaxHeap heap
) {
int parent
, child
;
int maxItem
, temp
;
if (isEmpty(heap
)) {
printf("Heap is Empty");
return ERROR
;
}
maxItem
= heap
->data
[1];
temp
= heap
->data
[heap
->size
--];
for (parent
= 1; parent
* 2 <= heap
->size
;parent
=child
) {
child
= parent
* 2;
if ((heap
->data
[child
] < heap
->data
[child
+1]) && child
!=heap
->size
) {
child
++;
}
if (temp
>= heap
->data
[child
]) break;
else heap
->data
[parent
] = heap
->data
[child
];
}
heap
->data
[parent
] = temp
;
return maxItem
;
}
void percDown(MaxHeap heap
, int p
) {
int parent
, child
;
int temp
;
temp
= heap
->data
[p
];
for (parent
= p
; parent
* 2 <= heap
->size
; parent
= child
) {
child
= parent
* 2;
if ((heap
->data
[child
] < heap
->data
[child
+ 1]) && child
!= heap
->size
) {
child
++;
}
if (temp
>= heap
->data
[child
]) break;
else heap
->data
[parent
] = heap
->data
[child
];
}
heap
->data
[parent
] = temp
;
}
void buildMaxHeap(MaxHeap heap
) {
for (int i
= heap
->size
/ 2; i
> 0; i
--) {
percDown(heap
, i
);
}
}
转载请注明原文地址: https://www.6miu.com/read-5030781.html