初始化
void HeapInit(Heap* heap, Compare compare){
if(heap == NULL || compare == NULL){
return;
}
heap->size = 0;
heap->cmp = compare;
return;
}
上浮调整函数
void AdjustUp(HeapType data[],size_t size,Compare cmp,size_t index){
if(index >= size){
return;
}
//1.
size_t child = index;
size_t parent = (index - 1) / 2;
while(child > 0){
//2.
if(cmp(data[child], data[parent])){
swap(&data[child],&data[parent]);
}
else{
break;
}
//3.
child = parent;
parent = (child - 1)/2;
}
//4.
}
下浮调整函数
void AdjustDown(HeapType data[],size_t size,Compare cmp,size_t index){
if(index >= size){
return;
}
size_t parent = index;
size_t child = 2 * parent + 1;
while(child < size){
if(child + 1 < size && cmp(data[child + 1] , data[child])){
child = child + 1;
}
if(cmp(data[child] , data[parent])){
swap(&data[child],&data[parent]);
}else{
break;
}
}
插入
void HeapInsert(Heap* heap, HeapType value){
if(heap == NULL){
return;
}
if(heap->size >= HeapMaxSize){
return;
}
heap->data[heap->size++] = value;
AdjustUp(heap->data, heap->size , heap->cmp, heap->size - 1);
}
取堆顶元素
int HeapRoot(Heap* heap, HeapType* value){
if(heap == NULL){
return 0;
}
if(heap->size == 0){
return 0;
}
*value = heap->data[0];
return 1;
}
删除元素
void HeapErase(Heap* heap){
if(heap == NULL){
return;
}
if(heap->size == 0){
return;
}
swap(&heap->data[0],&heap->data[heap->size - 1]);
--heap->size;
AdjustDown(heap->data,heap->size,heap->cmp,0);
}
堆的大小
size_t HeapSize(Heap* heap){
if(heap == NULL){
return 0;
}
return heap->size;
}
判空
int HeapEmpty(Heap* heap){
if(heap == NULL){
return;
}
return heap->size == 0 ? 1 : 0;
}
堆排序
void HeapSort(HeapType array[], size_t size){
if(size == 0 || size == 1 ){
return;
}
size_t heap_size = 0;
for(; heap_size < size; ++heapsize){
AdjustUp(array, heap_size, Less, heap_size);
++heap_size;
}
while(heap_size > 0){
swap(&array[0],&array[heap_size - 1]);
--heap_size;
AdjustDown(array, heap_size,Less,0);
}
return;
}