当前位置:网站首页>Heap sort and priority queue
Heap sort and priority queue
2022-07-03 06:24:00 【Brother laugh of roam】
Catalog
Two : Code implementation of the largest heap
Core function --- Stacking in and out
Constructor : Use arrays to construct heaps
The two constructors correspond to two heap sorts
One : What is a heap
The biggest pile :
Structurally, it is a Perfect binary tree
Numerical requirements : The value of the parent node >= The value of its child node
Two : Code implementation of the largest heap
Because the heap is a complete binary tree structure , So use The dynamic array To store the largest heap .
template<class Type> class maxHeap{ private: Type* data; int maxSize; int curSize; void doublespace(){ Type* tmp=data; maxSize*=2; data=new Type[maxSize]; for(int i=1;i<=curSize;i++){ data[i]=tmp[i]; } delete[] tmp; } };
Constructors + Destructor
public:
// Constructors
maxHeap(int initsize=5){
data=new Type[initsize+1];// Heap from 1 Start storage
maxSize=initsize;
curSize=0;
}
// Construct with array
template<typename T>
maxHeap(T a[],int n);
// Destructor
~maxHeap(){ delete[] data;}Core function --- Stacking in and out
Into the heap
// Into the heap template<class Type> void maxHeap<Type>::shiftUp(int k){ Type e=data[k]; for(k;k>1 && data[k/2]<e;k/=2){// Before the root node data[k]=data[k/2]; } data[k]=e; } template<class Type> void maxHeap<Type>::enHeap(const Type& x){ if(curSize==maxSize-1) doublespace(); data[++curSize]=x; shiftUp(curSize); }Ideas :
Put the element in the next position of the current heap length , And then for Maintain the structure of the heap , Conduct Adjust up
Be careful ---- from 1 When starting storage , Array number k Nodes at two locations , Its parent node k/2, Its left child k*2, The right child k*2+1
Out of pile
// Into the heap template<class Type> void maxHeap<Type>::shiftUp(int k){ Type e=data[k]; for(k;k>1 && data[k/2]<e;k/=2){// Before the root node data[k]=data[k/2]; } data[k]=e; } template<class Type> void maxHeap<Type>::enHeap(const Type& x){ if(curSize==maxSize-1) doublespace(); data[++curSize]=x; shiftUp(curSize); }The heap is a priority queue , therefore The root node is out of the heap , Then put the current stack The last node is placed on the root node , The length of the array -1, Then adjust downward from the root node .
Adjust the step down :
- Cyclic premise : The current node k At least there are left children (k*2<= The length of the array )
- use j To record the maximum value of left and right children :k The right child of exists, and then compare the values of the left and right children to get the maximum (if Conditions )
- Then decide whether to adjust : namely --- Judge the maximum value of the left and right children and the parent node , Maintenance of maximum reactor
- to update k=j, And then the cycle goes on
Constructor : Use arrays to construct heaps
// Construct with array template<typename T> maxHeap(T a[],int n){ // Be careful : Initialization of member variables maxSize=n+1; curSize=n; data=new Type[maxSize]; for(int i=1;i<=n;i++){ data[i]=a[i-1]; } // From the last non leaf node , Adjust downward one by one for(int j=n/2;j>=1;j--){// The root node should also be , Heap as 1 shiftDown(j); } }Ideas :
Store the array values into the heap array in turn , Then traverse from the first non leaf node to the root node , Perform downward adjustment every time . Be careful : from 1 The first non leaf node of the stored heap is curSize/2
The two constructors correspond to two heap sorts
template<typename T> void heapSort_one(T a[],int n){ maxHeap<int> heap; for(int i=0;i<n;i++){ heap.enHeap(a[i]); } for(int i=n-1;i>=0;i--){ a[i]=heap.deHeap(); } }template<typename T> void heapSort_arr(T a[],int n){ maxHeap<int> heap(a,n); for(int i=n-1;i>=0;i--){ a[i]=heap.deHeap(); } }
The whole program
maxheap.h
#ifndef my_Maxheap
#define my_Maxheap
template<class Type>
class maxHeap{
private:
Type* data;
int maxSize;
int curSize;
void doublespace(){
Type* tmp=data;
maxSize*=2;
data=new Type[maxSize];
for(int i=1;i<=curSize;i++){
data[i]=tmp[i];
}
delete[] tmp;
}
// Auxiliary function --- Adjust up and down
void shiftUp(int k);
void shiftDown(int k);
public:
// Constructors
maxHeap(int initsize=5){
data=new Type[initsize+1];// Heap from 1 Start storage
maxSize=initsize;
curSize=0;
}
template<typename T>
maxHeap(T a[],int n){
// Be careful : Initialization of member variables
maxSize=n+1;
curSize=n;
data=new Type[maxSize];
for(int i=1;i<=n;i++){
data[i]=a[i-1];
}
// From the last non leaf node , Adjust downward one by one
for(int j=n/2;j>=1;j--){// The root node should also be , Heap as 1
shiftDown(j);
}
}
// Destructor
~maxHeap(){ delete[] data;}
// Core function : Stacking in and out
void enHeap(const Type& x);// Heap is a priority queue , So put it in the back , Adjust up
Type deHeap();// The root node is out of the heap , Downward adjustments
};
// Into the heap
template<class Type>
void maxHeap<Type>::shiftUp(int k){
Type e=data[k];
for(;k>1 && data[k/2]<e;k/=2){// Before the root node
data[k]=data[k/2];
}
data[k]=e;
}
template<class Type>
void maxHeap<Type>::enHeap(const Type& x){
if(curSize==maxSize-1) doublespace();
data[++curSize]=x;
shiftUp(curSize);
}
// Out of pile
template<class Type>
void maxHeap<Type>::shiftDown(int k){
Type e=data[k];
int j;
while(k*2<=curSize){// Left child exists
j=k*2;
if(j+1<=curSize && data[j+1]>data[j]) j+=1;// Take the maximum value of left and right children
// Judge : Root node and max( Left and right children )
if(data[j]> e) data[k]=data[j];
else break;
// to update k value
k=j;
}
data[k]=e;
}
template<class Type>
Type maxHeap<Type>::deHeap(){
Type x=data[1];
data[1]=data[curSize--];
shiftDown(1);
return x;
}
#endifsortHelper.h
#include<ctime>
#include<cassert>
#include<iostream>
#include"maxheap.h"
using namespace std;
namespace sortHelper{
// Generating arrays
template<typename T>
T* gen_ran_arr(int n,int L,int R){
assert(L<=R);
srand(time(NULL));
T* arr=new T[n];
for(int i=0;i<n;i++){
arr[i]=rand()%(R-L)+1;
}
return arr;
}
// Print array
template<typename T>
void arr_print(T a[],int n){
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
/* Heap sort */
template<typename T>
void heapSort_one(T a[],int n){
maxHeap<int> heap;
for(int i=0;i<n;i++){
heap.enHeap(a[i]);
}
for(int i=n-1;i>=0;i--){
a[i]=heap.deHeap();
}
}
template<typename T>
void heapSort_arr(T a[],int n){
maxHeap<int> heap(a,n);
for(int i=n-1;i>=0;i--){
a[i]=heap.deHeap();
}
}
}Sort in place
Sort in place ----- Directly sort the heap in the original array , No additional space required , Therefore, the serial number is also 0 Start
stay 0 In the starting array :
- node k Parent node (k-1)/2, Left the child :2*k+1, The right child 2*k+2
- n The last non leaf node in the heap of nodes :(n-1)/2
template<typename T> void shiftDown_yuandi(T a[],int n,int k){ T e=a[k]; int j; while(k*2+1<n){ j=k*2+1; if(j+1<n && a[j+1]>a[j]) j+=1; if(a[j]>e) a[k]=a[j]; else break; k=j; } a[k]=e; } template<typename T> void heapSort_yuandi(T a[],int n){ // The original array is first adjusted into a heap for(int i=(n-1)/2;i>=0;i--){ shiftDown_yuandi(a,n,i); } // Move the top element back , Then adjust it into piles for(int i=n-1;i>0;i--){ swap(a[0],a[i]); shiftDown_yuandi(a,i,0); } }Be careful --- Don't talk about j It's defined in while Outside
边栏推荐
- 表达式的动态解析和计算,Flee用起来真香
- Click cesium to obtain three-dimensional coordinates (longitude, latitude and elevation)
- In depth learning
- Oauth2.0 - explanation of simplified mode, password mode and client mode
- 剖析虚幻渲染体系(16)- 图形驱动的秘密
- Zhiniu stock project -- 05
- opencv
- Important knowledge points of redis
- 认识弹性盒子flex
- JMeter linked database
猜你喜欢

輕松上手Fluentd,結合 Rainbond 插件市場,日志收集更快捷
![[system design] proximity service](/img/4a/2e68536cbe385af1d1a591e674fbf0.png)
[system design] proximity service

How to scan when Canon c3120l is a network shared printer

IE browser flash back, automatically open edge browser
![[5g NR] UE registration process](/img/e3/f881d51fba03010de8c45ea480f3f0.png)
[5g NR] UE registration process

Paper notes vsalm literature review "a comprehensive survey of visual slam algorithms"

Oauth2.0 - user defined mode authorization - SMS verification code login

Selenium - 改变窗口大小,不同机型呈现的宽高长度会不一样

Cesium Click to obtain the longitude and latitude elevation coordinates (3D coordinates) of the model surface

轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
随机推荐
Printer related problem record
Cannot get value with @value, null
Kubesphere - build Nacos cluster
Exportation et importation de tables de bibliothèque avec binaires MySQL
Migrate data from Mysql to tidb from a small amount of data
scroll-view指定滚动元素的起始位置
Cesium Click to obtain the longitude and latitude elevation coordinates (3D coordinates) of the model surface
Tabbar settings
数值法求解最优控制问题(一)——梯度法
Fluentd facile à utiliser avec le marché des plug - ins rainbond pour une collecte de journaux plus rapide
【无标题】8 简易版通讯录
Judge whether the date time exceeds 31 days
【5G NR】UE注册流程
Characteristics and isolation level of database
Kubernetes notes (IV) kubernetes network
Kubernetes notes (IX) kubernetes application encapsulation and expansion
UNI-APP中条件注释 实现跨段兼容、导航跳转 和 传参、组件创建使用和生命周期函数
Leetcode problem solving summary, constantly updating!
Une exploration intéressante de l'interaction souris - pointeur
Cesium entity (entities) entity deletion method