当前位置:网站首页>Heap sort [handwritten small root heap]
Heap sort [handwritten small root heap]
2022-07-06 12:57:00 【Classmate Chen_】
One 、 What is a heap ?
Heap is an efficient priority queue , We can think of the heap as an array of complete binary trees .
nature :
- The value of a node in the heap is always not greater than or less than the value of its parent node
- The heap is always a complete binary tree
The heap with the largest root node is called maximum heap or large root heap , The heap with the smallest root node is called the smallest heap or small root heap .
Algorithm idea and operation ( Take the small root pile for example ):
Put all the values to be sorted into each node of a complete binary tree , At this time, the binary tree does not have the nature of heap , utilize up perhaps down Operation to adjust the heap .
During the creation of the heap , We need to add two operations :
- Upward adjustment method (up)【 Building the heap 】
Adjust from the last node , Compare with its parent node , If it is smaller than the parent node , It does not conform to the nature of small root pile , So we need to exchange , Otherwise, there is no need to exchange .
After adjusting to a node , Regard the parent node of this node as the current node , Continue to make adjustments .
And so on , It can be adjusted into piles . - Downward adjustment method (down)
Set the parent node to fa, Left son for l, The right son is r.
From the last non-leaf node ( That is to say n/2 Nodes ) Start , use fa Respectively with l and r The comparison , The youngest son in exchange , If fa Is already the smallest , There is no need to exchange .
The same as the upward adjustment method , After adjustment , From the youngest son as fa, Continue to do downward adjustment .
Why start with the last non leaf node down Well ?
The value in the figure is the node number , Altogether 9 Nodes , that n=9, So from n/2 Start adjusting from the fourth node ( Red nodes ).
Why is that ?
Because what we do is down operation , So in order to adjust to all points , It must be adjusted to the last leaf node . It happens that the parent node of the last leaf node is the n/2 Nodes , from n/2 Nodes start down, It will definitely adjust to all points .
Let's take a look at the simulation process :
Initial state diagram
Now we have built a small root pile ( Note that small root pile and large root pile are not unique , Just meet the nature )
Next, use the heap to sort :
subject : Heap sort
Enter a length of n n n The whole number sequence of , From small to large, before output m m m Small number .
Input format
The first line contains integers n n n and m m m.
The second line contains n It's an integer , Represents an integer sequence .
Output format
All in one line , contain m m m It's an integer , Represents the first in an integer sequence m Small number .
Data range
1 ≤ m ≤ n ≤ 105 1≤m≤n≤105 1≤m≤n≤105,
1 ≤ Count Column in element plain ≤ 109 1≤ The elements in the sequence ≤109 1≤ Count Column in element plain ≤109
sample input :
5 3
4 5 1 3 2
sample output :
1 2 3
Topic ideas :
This question is to output the top k Number , Because heap is not guaranteed from left to right 、 The order from top to bottom is increasing , For example, the third number in the figure below is 5, Actually, the third number should be 4, So we can't build a heap and output it directly before k A digital .
So you can delete nodes ( It's not really deletion ) To implement heap sorting , Which node is more appropriate to delete , Obviously, it can't be the front and middle nodes , Because deleting the previous node in the heap is very troublesome , But deleting the last node is easy . Can I delete the last node ? The answer is yes , Because the top element is guaranteed to be the smallest , So every time you output the top of the heap element, you can exchange the top of the heap element with the last element , At this time, the smallest element becomes the last element , You can delete it ( I can't use it anymore ), Then start with the top element down operation , Therefore, we can find that the nature of the heap can still be maintained , So you can delete the last node to sort the heap .
Heap storage :
In order to facilitate storage and implementation , Heaps can usually be modeled using arrays .
fa: Parent node ,l: Left second son ,r: Right son
set up f a = x fa=x fa=x, be l = 2 ∗ x l=2*x l=2∗x, r = 2 ∗ x + 1 r=2*x+1 r=2∗x+1
AC Code (C++):
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=1e5+10;
int q[N],numbers,n,m;
void down(int x){
int t=x;
if(x*2<=numbers && q[x*2]<q[t]) t=x*2;
if(x*2+1<=numbers && q[x*2+1]<q[t]) t=x*2+1;
if(t!=x){
swap(q[t],q[x]);
down(t);
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&q[i]);
numbers=n; // The number of remaining nodes after deleting a node
for(int i=n/2;i;i--) down(i);
while(m--){
printf("%d ",q[1]);
q[1]=q[numbers];
numbers--;
down(1);
}
return 0;
}
边栏推荐
- [GNSS] robust estimation (robust estimation) principle and program implementation
- Itext 7 生成PDF总结
- Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY
- PRIDE-PPPAR源码解析
- InnoDB dirty page refresh mechanism checkpoint in MySQL
- [algorithm] sword finger offer2 golang interview question 8: the shortest subarray with a sum greater than or equal to K
- MySQL error warning: a long semaphore wait
- In 2020, the average salary of IT industry exceeded 170000, ranking first
- [算法] 剑指offer2 golang 面试题3:前n个数字二进制形式中1的个数
- [Chongqing Guangdong education] reference materials for regional analysis and planning of Pingdingshan University
猜你喜欢
[算法] 剑指offer2 golang 面试题13:二维子矩阵的数字之和
Implementation of Excel import and export functions
Unity3d makes the registration login interface and realizes the scene jump
Idea problem record
[Chongqing Guangdong education] Shandong University College Physics reference materials
服务未正常关闭导致端口被占用
In 2020, the average salary of IT industry exceeded 170000, ranking first
(core focus of software engineering review) Chapter V detailed design exercises
KF UD分解之UD分解基础篇【1】
[algorithm] sword finger offer2 golang interview question 12: the sum of the left and right sub arrays is equal
随机推荐
Introduction to the daily practice column of the Blue Bridge Cup
FairyGUI按钮动效的混用
FairyGUI循環列錶
Database table splitting strategy
[algorithm] sword finger offer2 golang interview question 4: numbers that appear only once
Detailed explanation of balanced binary tree is easy to understand
Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
(课设第一套)1-5 317号子任务 (100 分)(Dijkstra:重边自环)
There is no red exclamation mark after SVN update
编辑距离(多源BFS)
Devops' future: six trends in 2022 and beyond
MySQL shutdown is slow
Game 280 weekly
第一人称视角的角色移动
Excel导入,导出功能实现
Solution to the problem of automatic login in Yanshan University Campus Network
地球围绕太阳转
堆排序【手写小根堆】
Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY
[算法] 剑指offer2 golang 面试题4:只出现一次的数字