当前位置:网站首页>Detailed explanation of heap sorting
Detailed explanation of heap sorting
2022-07-06 08:35:00 【So, dream】
What is a heap ?
A heap is a complete binary tree 「 That is, the subscript of each node is consistent with that of the full binary tree node 」
Depending on the nature of the heap , You can divide the heap into Big root pile and Heap
- Big root pile : The value of each node is greater than or equal to the value of its left and right children
- Heap : The value of each node is less than or equal to the value of its left and right children
Above is a big pile , We can map it to an array array in
According to the nature of big root pile , We can easily draw the following conclusion :
array[i] >= array[2 * i + 1] && array[i] >= array[2 * i + 2]
The basic idea of heap sorting
Heap sorting can be roughly divided into three steps :
- Build the array to be sorted into a large root heap , In this way, the element at the top of the heap is the largest element .
- Exchange the top element with the last element , then The last element will be removed The remaining nodes of are reconstructed into a large root heap
- Repeat step 2 , Until the sorting is complete .「 You can get the largest element for the first time , The second time you can get the second largest element , And so on 」
analogy : The process is like , Find the tallest one in a group , Let him exchange seats with the people in the last row ; Then find the second tallest among the rest , Let him exchange seats with the person sitting in the penultimate row ; And so on .
Detailed implementation of heap sorting
Suppose the array to be sorted array =[5,8,2,4,3,6,7,1]
1 Build the array to be sorted into a large root heap
First , Turn the array to be sorted into a complete binary tree
Next , We need to make sure : The value of each node is larger than that of its left and right children . Here you might think , We can start from the top , Compare the size relationship between parent and child nodes , Put the larger element on the parent node . This method seems to be right , But in the process of traversing from top to bottom , The child nodes of the upper layer may be replaced by larger values , As a result, some child nodes are larger than their parent nodes 「 That is, the maximum value at the top of the heap cannot be guaranteed 」. As shown in the figure below
therefore , We must compare from bottom to top . So , We need to find the last parent node , Then flashback to sort out the size relationship between parent and child nodes . So how to find the last parent node ? because , In the big pile array[i] >= array[2 * i + 1] && array[i] >= array[2 * i + 2]
, So when the leaf node coordinates are length - 1
when **「 The leaf node with the largest subscript 」**, The coordinates of its parent node are (length / 2) - 1
.「 according to i * 2 + 1 = length - 1
and i * 2 + 2 = length - 1
」
After finding the last parent node , Compare it with the values of the left and right nodes , If the value of the left and right nodes is greater than it , Exchange the larger value of the left and right nodes with it ; Otherwise, no operation will be carried out , about array , Will exchange 7 and 2 The location of
Then exchange 8 and 5 The location of
Be careful , If after switching nodes , The child node of the next layer is larger than the parent node , Continue to exchange .
Exchange the top element with the last element , then The last element will be removed The remaining nodes of are reconstructed into a large root heap
Swap the top element with the last element
- Repeat step 2 , Until the sorting is complete .
Let's use a dynamic graph to feel the whole process
Code implementation
Kotlin
class Solution {
fun heapSort(array: IntArray) {
if (array.isEmpty()) return
var length = array.size
buildMaxHeap(array, length)
for (i in length - 1 downTo 0) {
// This can be written as downTo 1 Because of 1 Time has been exchanged
swap(array, 0, i) // Swap the root top and the current last element
length--
heapify(array,0,length) // Because of the exchange , The condition of large root heap may not be met , Adjust the top element
}
}
private fun buildMaxHeap(array: IntArray, length: Int) {
val fatherIndex = (length / 2) + 1 // Find the subscript of the last parent node
for (i in fatherIndex downTo 0) {
heapify(array, i, length)
}
}
private fun swap(array: IntArray, i: Int, j: Int) {
val temp = array[i]
array[i] = array[j]
array[j] = temp
}
private fun heapify(array: IntArray, i: Int, length: Int) {
val left = 2 * i + 1 // The left node
val right = 2 * i + 2 // Right node
var largeIndex = i // The subscript of the parent node corresponding to the maximum value in the left and right nodes
if (left < length && array[left] > array[largeIndex]) largeIndex = left
if (right < length && array[right] > array[largeIndex]) largeIndex = right
if (largeIndex != i) {
swap(array, largeIndex, i) // After exchanging , It may cause that the lower layer is not a big pile
heapify(array, largeIndex, length)
}
}
}
边栏推荐
猜你喜欢
根据csv文件某一列字符串中某个数字排序
Yyds dry goods inventory three JS source code interpretation eventdispatcher
被破解毁掉的国产游戏之光
2022.02.13 - NC001. Reverse linked list
Configuring OSPF load sharing for Huawei devices
JVM performance tuning and practical basic theory - Part 1
Summary of phased use of sonic one-stop open source distributed cluster cloud real machine test platform
MySQL learning records 12jdbc operation transactions
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
C语言双指针——经典题型
随机推荐
sublime text中conda环境中plt.show无法弹出显示图片的问题
2022 Inner Mongolia latest water conservancy and hydropower construction safety officer simulation examination questions and answers
Golang force buckle leetcode 1020 Number of enclaves
The mysqlbinlog command uses
生成器参数传入参数
Rviz仿真时遇到机器人瞬间回到世界坐标原点的问题及可能原因
logback1.3. X configuration details and Practice
leetcode刷题 (5.31) 字符串
How to conduct interface test? What are the precautions? Nanny level interpretation
角色动画(Character Animation)的现状与趋势
Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
优秀的软件测试人员,都具备这些能力
Precise query of tree tree
C語言雙指針——經典題型
Report on Market Research and investment prospects of China's silver powder industry (2022 Edition)
游戏解包的危害及资源加密的重要性
Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
Visual implementation and inspection of visdom
China dihydrolaurenol market forecast and investment strategy report (2022 Edition)
String to leading 0