当前位置:网站首页>Heap (priority queue)
Heap (priority queue)
2022-07-02 12:08:00 【The dishes are not right】

Catalog
🥬 Downward adjustment of the heap
🥬 The nature of the heap

summary : One Perfect binary tree With Sequence traversal Method is put into the array to store , The main use of this method is the representation of the heap .
🥬 The classification of heaps


🥬 Downward adjustment of the heap
Now there's an array , Logically, it is a complete binary tree , We pass from The root node At the beginning Downward adjustments The algorithm can adjust it into a small heap or a large heap . The downward adjustment algorithm has a premise : The left and right subtrees must be a heap , To adjust .
Take a small pile as an example :
1、 Let the left and right children compare , Minimum value .
2、 Compare the younger child node with the father node , If the child node < Father node , In exchange for , conversely , Don't swap .
3、 cycle , If the subscript of the child node is out of bounds , It means the end has come , ends .

Code example :
//parent: The root node of each tree
//len: The adjusted end position of each tree
public void shiftDown(int parent,int len){
int child=parent*2+1; // Because the heap is a complete binary tree , If there is no left child, there must be no right child , So at least there are left children , There are at least 1 A child
while(child<len){
if(child+1<len && elem[child]<elem[child+1]){
child++;// Compare the two child nodes and take the smaller value
}
if(elem[child]<elem[parent]){
int tmp=elem[parent];
elem[parent]=elem[child];
elem[child]=tmp;
parent=child;
child=parent*2+1;
}else{
break;
}
}
}🥬 Establishment of heap
public void creatHeap(int[] arr){
for(int i=0;i<arr.length;i++){
elem[i]=arr[i];
useSize++;
}
for(int parent=(useSize-1-1)/2;parent>=0;parent--){// Array index from 0 Start
shiftDown(parent,useSize);
}
}The space complexity of pile building is O(N), Because the pile is a complete binary tree , A full binary tree is also a complete binary tree , We use a full binary tree ( In the worst case ) To prove .

🥬 Stack up adjustment
Now there is a heap , We need to insert data at the end of the heap , Then adjust it , Keep it in the heap structure , This is upward adjustment .
Take a large pile as an example :

Code example :
public void shiftup(int child){
int parent=(child-1)/2;
while(child>0){
if(elem[child]>elem[parent]){
int tmp=elem[parent];
elem[parent]=elem[child];
elem[child]=tmp;
child=parent;
parent=(child-1)/2;
}else{
break;
}
}
}🥬 Common operation of heap
Queue entry
Add elements to the heap , Is to add to the last position , And then it's going up .
public boolean isFull(){
return elem.length==useSize;
}
public void offer(int val){
if(isFull()){
elem= Arrays.copyOf(elem,2*elem.length);// Capacity expansion
}
elem[useSize++]=val;
shiftup(useSize-1);
}Outgoing queue
Delete the elements in the heap , Just exchange the top element with the last element , Then reduce the size of the entire array by one , Finally, adjust downward , The top element of the stack is deleted .
public boolean isEmpty(){
return useSize==0;
}
public int poll(){
if(isEmpty()){
throw new RuntimeException(" Priority queue is empty ");
}
int tmp=elem[0];
elem[0]=elem[useSize-1];
elem[useSize-1]=tmp;
useSize--;
shiftDown(0,useSize);
return tmp;
}Get team leader elements
public int peek() {
if (isEmpty()) {
throw new RuntimeException(" Priority queue is empty ");
}
return elem[0];
}🥬TopK problem
Here you are. 6 Data , Seek before 3 Maximum data . At this time, how do we do with heaps ?
Their thinking :
1、 If you ask before K The biggest element , To build a small root pile .
2、 If you ask before K The smallest element , To build a big pile .
3、 The first K Big elements . Build a small pile , The top of the heap element is the second K Big elements .
4、 The first K Small elements . Build a lot of , The top of the heap element is the second K Big elements .
for instance : Seek before n Maximum data

Code example :
public static int[] topK(int[] array,int k){
// Create a size of K Small roots
PriorityQueue<Integer> minHeap=new PriorityQueue<>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
// Traverse the elements in the array , Before the k Put elements in the queue
for(int i=0;i<array.length;i++){
if(minHeap.size()<k){
minHeap.offer(array[i]);
}else{
// from k+1 Elements start , Compare with the heap top elements respectively
int top=minHeap.peek();
if(array[i]>top){
// Pop up before saving
minHeap.poll();
minHeap.offer(array[i]);
}
}
}
// Put the elements in the heap into the array
int[] tmp=new int[k];
for(int i=0;i< tmp.length;i++){
int top=minHeap.poll();
tmp[i]=top;
}
return tmp;
}
public static void main(String[] args) {
int[] array={12,8,23,6,35,22};
int[] tmp=topK(array,3);
System.out.println(Arrays.toString(tmp));
}result :

Array sorting
Moreover, if you want to sort an array from small to large , Should we rely on big root pile or small root pile ?
----> Big root pile

Code example :
public void heapSort(){
int end=useSize-1;
while(end>0){
int tmp=elem[0];
elem[0]=elem[end];
elem[end]=tmp;
shiftDown(0,end);// Suppose we adjust it down to the big root heap
end--;
}
}🥬 Summary
That's what we have today , If you have any questions, please leave a message in the comments area

边栏推荐
- H5,为页面添加遮罩层,实现类似于点击右上角在浏览器中打开
- 行業的分析
- On data preprocessing in sklearn
- Natural language processing series (III) -- LSTM
- Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
- PyTorch中repeat、tile与repeat_interleave的区别
- PyTorch nn.RNN 参数全解析
- HR wonderful dividing line
- GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
- 【工控老马】西门子PLC Siemens PLC TCP协议详解
猜你喜欢

倍增 LCA(最近公共祖先)

堆(優先級隊列)

GGPlot Examples Best Reference

From scratch, develop a web office suite (3): mouse events

How to Create a Beautiful Plots in R with Summary Statistics Labels

小程序链接生成

自然语言处理系列(二)——使用RNN搭建字符级语言模型

Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
![[visual studio 2019] create and import cmake project](/img/51/6c2575030c5103aee6c02bec8d5e77.jpg)
[visual studio 2019] create and import cmake project

还不会安装WSL 2?看这一篇文章就够了
随机推荐
基于Arduino和ESP8266的连接手机热点实验(成功)
Mish-撼动深度学习ReLU激活函数的新继任者
5g era, learning audio and video development, a super hot audio and video advanced development and learning classic
Yygh-10-wechat payment
(C language) octal conversion decimal
[C language] Yang Hui triangle, customize the number of lines of the triangle
Maximum profit of jz63 shares
conda常用命令汇总
Filtre de profondeur de la série svo2
倍增 LCA(最近公共祖先)
Leetcode122 the best time to buy and sell stocks II
Natural language processing series (III) -- LSTM
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
ESP32 Arduino 引入LVGL 碰到的一些问题
YYGH-BUG-05
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
YYGH-BUG-04
二分刷题记录(洛谷题单)区间的甄别
(C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
史上最易懂的f-string教程,收藏這一篇就够了