堆
堆
0x00 什么是堆
计算机中,当有很多任务要完成时,并不是先到先处理,而是按照优先级的顺序,优先级高的先处理,这是一种优先队列
如果用前面所学的数据结构来实现,时间复杂度如下:
以上是知乎用户的解释截图,可以知道调整堆(也就是完全二叉树的形式已经建立好了)的时间复杂度为O(n),而一个一个插入进去来建立堆的时间复杂度为nlogn
0x01 堆的抽象数据类型
0x02 堆的操作实现
#include <stdio.h>
#include <stdlib.h>
#define maxsize 1000
#define hugenum 1000
typedef struct heapstruct* maxheap;
struct heapstruct{
int* data;
int capacity;
int size;
};
maxheap create(void){
maxheap ret=(maxheap)malloc(sizeof(struct heapstruct));
ret->capacity=maxsize;
ret->data=(int*)malloc(sizeof(int)*(ret->capacity+1));
ret->size=0;
ret->data[0]=hugenum;
return ret;
}
maxheap insert(maxheap h,int x){
if(h->size==h->capacity){
printf("堆满!\n");
}else{
h->data[++h->size]=x;
int child=h->size;
int parent=child/2;
while(h->data[child]>h->data[parent]){
int temp=h->data[child];
h->data[child]=h->data[parent];
h->data[parent]=temp;
child=parent;
parent=child/2;
}
}
return h;
}
int del(maxheap h){
int ret;
if(h->size){
ret=h->data[1];
h->data[1]=h->data[h->size];
h->size--;
int parent=1;
int child=2*parent;
for(;child<=h->size;){
int max=h->data[child];//默认左子树最大
int pos =child;
if((child+1)<=h->size&&h->data[child+1]>h->data[child]){
max=h->data[child+1];
pos=child+1;
}
if(h->data[parent]>=max){
break;
}else{
int temp=h->data[parent];
h->data[parent]=max;
h->data[pos]=temp;
parent=pos;
child=2*parent;
}
}
}else{
printf("堆空!");
}
return ret;
}
以上代码验证通过