STL源码—heap最大堆,最小堆(TT)
来源:互联网 发布:js json特殊字符处理 编辑:程序博客网 时间:2024/05/22 00:53
最大堆和最小堆都是一棵完全二叉树。
最大堆:是指根节点的关键字值是堆中的最大关键字值,且每个节点若有儿子节点,其关键字值都不小于其儿子节点的关键字值。
最小堆:是指根节点的关键字值是堆中的最小关键字值,且每个节点若有儿子节点,其关键字值都不大于其儿子节点的关键字值。
最大堆的插入操作
步骤:
- 把当前节点数i设置为已知堆的节点数加1即i=++(*n),即新增的元素放在最下一层作为新的叶子节点。求出节点i的父节点parent=i/2;判断是否为空堆,并比较所插入元素与父节点关键字值的大小;
- 若所插入节点关键字值大于父节点关键字值即item>heap[parent],则把父节点向下移,并把父节点作为当前节点,依次求父节点,即依次沿着树枝向上延伸;
- 把元素item插入到正确位置;
最大堆的删除操作
最大堆的删除,即删除最大的元素。我们先取最后的元素提到根结点,然后删除最大值,然后再把新的根节点放到合适的位置。
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX_SIZE 10
- int heap[MAX_SIZE];
- /*最大堆的插入操作*/
- /*注:堆的下标是从1开始,而不是0*/
- void max_Heap_insert(int *heap,int *n,int item)
- {
- int i,parent;//i为当前节点,parent为i的父节点
- if((*n)==MAX_SIZE)//堆为满
- {
- printf("The heap is full\n");
- exit(1);
- }
- i=++(*n);
- parent=i/2;
- while((i!=1) && (item>heap[parent]))//若堆为非空,且所插入数据item大于父节点的关键字值
- {
- heap[i]=heap[parent];//父节点关键字值下移
- i=parent;//把父节点作为当前节点
- parent/=2;//依次求父节点
- }
- heap[i]=item;//插入到正确的位置
- }
- /*最大堆的删除操作*/
- int max_Heap_delete(int *heap,int *n)
- {
- int item,temp;
- int child,parent;
- if(*n==0)//若为空堆
- {
- printf("The heap is empty.\n");
- exit(1);
- }
- item=heap[1];//把最大堆的最大元素赋给item
- temp=heap[(*n)--];//堆的最后节点关键字值
- parent=1;
- child=2*parent;
- while(child<=(*n)) //<循环次数的限制
- {
- if(child<*n && heap[child]<heap[child+1])
- child++;//找出堆中最大关键字值的节点
- if(temp>=heap[child])break;//把最大节点关键字值与最后节点关键字值比较
- else
- {//若堆中存在比最后节点关键字值大的节点,则交换位置
- heap[parent]=heap[child];
- parent=child;
- child*=2;
- }
- }
- heap[parent]=temp;//插入到正确位置
- return item;//返回删除的关键字值
- }
- int main()
- {
- int item,i;
- int n=0;
- for(i=1;i<MAX_SIZE;i++)
- {
- scanf("%d",&item);
- max_Heap_insert(heap,&n,item);
- }
- for(i=1;i<=n;i++)
- printf("%d ",heap[i]);
- printf("\n");
- item=max_Heap_delete(heap,&n);
- printf("The deleted data is:%d",item);
- printf("\n");
- for(i=1;i<=n;i++)
- printf("%d ",heap[i]);
- return 0;
- }
输出:
1 2 32 12 55 334 7 23 7 67
334 32 55 23 12 2 7 1 7
The deleted data is:334
55 32 7 23 12 2 7 1
0 0
- STL源码—heap最大堆,最小堆(TT)
- STL源码—heap最大堆,最小堆
- STL源码剖析——最大堆heap
- 最小堆和最大堆 heap (zz)
- 最大堆(max-heap)和最小堆(min-heap)
- STL 最大堆、最小堆的应用
- Sturcture.Heap 堆(最大堆实现(最小堆实现类似))
- STL系列——堆(heap)
- 双端堆/最小-最大堆/Double-Ended Heap ?
- 最大堆(最小堆)C++实现源码
- 堆,最大堆,最小堆,最大左高树 源码
- STL——heap堆
- STL——堆heap
- 最大堆 最小堆 poj2442 STL堆的使用
- 最大堆 最小堆 poj2442 STL堆的使用
- 哈理工oj 最小的n个和【heap/最大堆的STL实现】
- 最大堆/最小堆
- 最小堆。最大堆。
- x86架构下的系统段描述符格式
- poj解题报告——3080
- Qt浅谈之电子时钟
- JS设置超时时将被挂起
- unity学习1
- STL源码—heap最大堆,最小堆(TT)
- 星号字-------------杨-------------
- Qt浅谈之钟表(时分秒针)
- 欢迎您在新浪博客安家
- 开通新浪博客
- 霍尼威尔面试有感
- Qt浅谈之内存泄露
- block
- 悼念512汶川大地震遇难同胞——一定要记住我爱你(数学函数floor和ceil的应用)