优先队列

插入时间复杂度O(logN)


#define swap(a, b) {\
	__typeof(a) __temp = a;\
	a = b, b = __temp;\
}

typedef struct priority_queue {
	int *data;
	int cnt, size;
} priority_queue;

priority_queue *init(int n) {
	priority_queue *q = (priority_queue *)malloc(sizeof(priority_queue));
	q->data = (int *) malloc(sizeof(int) * (n+1));
	q->cnt = 0;
	q->size = n;
	return q;
}

int empty(priority_queue *q) {
	return q->cnt == 0;
}

int top(priority_queue *q) {
	return q->data[1];
}

int push(priority_queue *q, int val) {
	if (!q) return 0;
	if (q->cnt == q->size) return 0;
	q->data[++(q->cnt)] = val;
	int ind = q->cnt;
	while (ind >> 1 && q->data[ind] > q->data[ind >> 1]) {
		swap(q->data[ind], q->data[ind >> 1]);
		ind >>= 1;
	}

	return 1;
}

int pop(priority_queue *q) {
	if (!q) return 0;
	if (empty(q)) return 0;
	q->data[1] = q->data[q->cnt--];
	int ind = 1;
	while ((ind << 1) <= q->cnt) {
		int temp = ind, l = ind << 1, r = ind << 1 | 1;
		if (q->data[l] > q->data[temp]) temp = l;
		if (r <= q->cnt && q->data[r] > q->data[temp]) temp = r;
		if (temp == ind) break;
		swap(q->data[temp] , q->data[ind]);
		ind = temp;
	}
	return 1;
}

void clear(priority_queue *q) {
	if (!q) return ;
	free(q->data);
	free(q);
	return ;
}

int main() {
	srand(time(0));
#define max_op 20
	priority_queue *q = init(max_op);
	for (int i = 0; i < max_op; i++) {
		int val = rand() % 100;
		push(q, val);
		printf("%d ", val);
	}
	printf("\n");
	for (int i = 0; i < max_op; i++) {
		printf("%d ", top(q));
		pop(q);
	}
	printf("\n");
#undef max_op
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值