数据结构与算法-优先队列

本文介绍了优先队列的概念,它是一种特殊的队列,高优先级的元素先出。优先队列通常通过堆来实现,这里使用C语言展示了如何用数组实现完全二叉树结构的堆,并实现了插入、删除和打印操作。代码中详细解释了插入时的向上浮动和删除时的向下浮动过程。

优先队列

(一)优先队列

1.一种特殊的队列,数据满足优先级高的先出

  • 队列
  • 高优先级先出,入队顺序随便

2.实现方式:堆

  • 用数组实现完全二叉树
    • 节省空间
    • 插入、删除、查找速度快
  • 子节点都比父节点大(高优先级的在后面)

(二)编程实现

1.C语言

思路:

(1) 数组实现完全二叉树

(2) 插入时向上浮动(二分查找)

(3) 删除时向下浮动(二分查找)

#include <stdio.h>
#include <stdlib.h>

typedef int Elem;

struct heap {
	
	Elem* data;
	int capacity;
	int size;
};

typedef struct heap* Heap;

Heap initHeap(int capacity){
	
	Heap h;
	h = (Heap)malloc(sizeof(struct heap));
	if(!h) h = NULL;
	h->data = (Elem*)malloc(sizeof(Elem)*(capacity+1));
	if(!h->data) h = NULL;
	h->capacity = capacity;
	h->size = 0;
	return h;
}

void printHeap(Heap h){
	
	for(int i = 1;i <= h->size;i++)
		printf("%d",h->data[i]);
}

int isFull(Heap h){
	
	int flag = 0;
	if(h->size == h->capacity)
		flag = -1;
	return flag;
	
}

void percolateUp(Heap h,int index){
	
	int i;
	h->data[0] = h->data[index];
	for(i = index;(i > 1) && (h->data[0] < h->data[i/2]);i/=2)
	{
		h->data[i] = h->data[i/2];
	}
	
	h->data[i] = h->data[0];
	
}
int insertHeap(Heap h,Elem data){
	
	int flag = 0;
	if(isFull(h))
		flag = -1;
	h->data[++h->size] = data;
	percolateUp(h,h->size);
	
	return flag;
}

int isEmpty(Heap h){
	
	int flag = 0;
	if(h->size == 0)
		flag = -1;
	return flag;
}

void percolateDown(Heap h,int index){
	
	h->data[0] = h->data[index];
	int i,child = 1;
	//向下过滤,直到找到最小的节点(可能为左儿子或右儿子)或者越界
	for(i = index;i*2 <= h->size;i = child)
	{
		child = i*2;
		if(h->data[child] > h->data[child+1] && child!=h->size)
			child++;
		if(h->data[child] < h->data[0])
			h->data[i] = h->data[child];
		else
			break;
	}
	h->data[i] = h->data[0];
}
int removeHeap(Heap h,Elem* data){
	
	int flag = 0;
	if(isEmpty(h))
		flag = -1;
	
	h->data[1] = h->data[h->size--];
	percolateDown(h,1);
	return flag;
}


int main()
{
   /*  Write C code in this online editor and run it. */
    Heap h = initHeap(10);
    insertHeap(h,5);
    insertHeap(h,4);
	insertHeap(h,6);
	insertHeap(h,3);
	insertHeap(h,1);
	insertHeap(h,2);
	
	Elem x;
	removeHeap(h,&x);
	

    printHeap(h);
   
   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值