#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define HEAP_LEN 100
typedef struct _heapElem{
int pr; // 값이 작을수록 높은 우선순위
char data;
} HeapElem;
int numOfData;
HeapElem heap[HEAP_LEN];
void HeapInit(){
numOfData = 0;
}
int HIsEmpty(){
if(numOfData == 0)
return TRUE;
else
return FALSE;
}
int GetParentIDX(int idx) {
return idx/2;
}
int GetLChildIDX(int idx){
return idx*2;
}
int GetRChildIDX(int idx){
return GetLChildIDX(idx)+1;
}
int GetHiPriChildIDX(int idx){
if(GetLChildIDX(idx) > numOfData){ // 자식 노드가 없다면
return 0;
}
else if(GetLChildIDX(idx) == numOfData){ // 왼쪽 자식 노드가 마지막 노드라면
return GetLChildIDX(idx);
}
else{ // 왼쪽 자식 노드와 오른쪽 자식 노드의 우선순위를 비교
if(heap[GetLChildIDX(idx)].pr > heap[GetRChildIDX(idx)].pr)
return GetRChildIDX(idx);
else
return GetLChildIDX(idx);
}
}
void HInsert(char data, int pr){//root노드의 idx = 1
int idx = numOfData + 1;
HeapElem nelem = {pr, data};
while(idx != 1){
if(pr < (heap[GetParentIDX(idx)].pr)){
heap[idx] = heap[GetParentIDX(idx)];
idx = GetParentIDX(idx);
}
else{
break;
}
}
heap[idx] = nelem;
numOfData += 1;
}
char HDelete()
{
char retData = heap[1].data; // 삭제할 데이터 임시 저장
HeapElem lastElem = heap[numOfData];
int parentIdx = 1; // 루트 노드의 Index
int childIdx;
while(childIdx = GetHiPriChildIDX(parentIdx))
{
if(lastElem.pr <= heap[childIdx].pr)
break;
heap[parentIdx] = heap[childIdx];
parentIdx = childIdx;
}
heap[parentIdx] = lastElem;
numOfData -= 1;
return retData;
}
int main(void)
{
HeapInit();
HInsert('A', 1);
HInsert('B', 2);
HInsert('C', 3);
printf("%c \n", HDelete());
HInsert('D', 1);
HInsert('E', 2);
HInsert('F', 3);
printf("%c \n", HDelete());
while(!HIsEmpty())
printf("%c \n", HDelete());
return 0;
}