初始化

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值