#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#define swap(a,b) do{typeof(a) t=a; a=b; b=t;}while(0)
typedef struct Heap
{
int* arr;
size_t cal;
size_t cnt;
}Heap;
void _create_heap(int arr[],int root,size_t len)
{
while(root*2 <= len)
{
int max = root*2;
if(max+1 <=len && arr[max-1] < arr[max])
max++;
if(arr[root-1] > arr[max-1])
return;
swap(arr[root-1],arr[max-1]);
root = max;
}
}
Heap* create_heap(size_t len)
{
Heap* heap = malloc(sizeof(Heap));
heap->arr = malloc(sizeof(heap->arr[0])*len);
heap->cal = len;
heap->cnt = 0;
return heap;
}
void show_heap(Heap* heap)
{
for(int i=0; i<heap->cnt; i++)
{
printf("%d ",heap->arr[i]);
}
printf("\n");
}
bool empty_heap(Heap* heap)
{
return 0 == heap->cnt;
}
int top_heap(Heap* heap)
{
return heap->arr[0];
}
void pop_heap(Heap* heap)
{
heap->arr[0] = heap->arr[--heap->cnt];
_create_heap(heap->arr,1,heap->cnt);
}
void push_heap(Heap* heap,int data)
{
heap->arr[heap->cnt++] = data;
for(int i=heap->cnt/2; i>0; i--)
{
_create_heap(heap->arr,i,heap->cnt);
}
}
void sort_heap(Heap* heap)
{
for(int i=heap->cnt-1; i>1; i--)
{
swap(heap->arr[0],heap->arr[i]);
_create_heap(heap->arr,1,i);
}
}
int main(int argc,const char* argv[])
{
srand(time(NULL));
Heap* heap = create_heap(20);
for(int i=0; i<15; i++)
{
push_heap(heap,rand()%90+10);
}
show_heap(heap);
sort_heap(heap);
show_heap(heap);
}