Heap (heap) of commonly used data structures

1 Introduction

           Following the previous article on  arrays and linked lists , let's talk about it today. We all know that there is a concept of stack in the operating system, and students who have studied java know that there is also a stack in the java virtual machine. The stack is responsible for managing the context of the function and some basic types of variables, which is managed by the system. The heap stores the newly created object, and will point its address to a reference variable in the stack. If there is no reference, the object becomes a garbage object and is finally collected by the garbage collector. But what I want to talk about here is not the heap in memory. Memory is generally managed in the form of a linked list. But the concept of heap in the data structure is equivalent to a priority queue.

2. Definition and nature of heap

   1. Definition

           A heap is a complete binary tree . The so-called complete binary tree refers to the position of each node in the tree and the position in the full binary tree . The so-called full binary tree refers to the maximum value of nodes in each layer of the tree (that is, the tree Every layer of is filled);

           Maximum heap : the value of the parent node in a heap is always larger than the child node (priority queue)

           Minimum heap : the value of the parent node is always smaller than the child node

                                  

     2. Nature-node position relationship

              1. It is known that the position of the parent node is i, the position of the left child node is 2i+1, and the position of the right child node is 2i+2

              2. It is known that the position of the child node is i, and the position of its parent node is (i-1)/2

     3. Nature two height

              The height of the heap is the number of steps from the root node to the farthest leaf node, which is equal to the number of layers of the heap minus one. Assuming that there are a total of n nodes, the height of the heap composed of these n nodes is floor(logn), where the logarithm is base two.

              If the bottom layer of the heap is filled, the number of nodes on the smallest layer is 2^{h}, the sum of the nodes of all the previous layers is 2^{h}-1, then the total number of nodes in this heap is2^{h+1}-1

     4. The process of heap construction

             As shown in the figure, we build a minimum heap, and the implementation process is to insert each element into the last bit of the heap, and then continue to perform the heap operation upwards. The following code implementation will reflect this more clearly.

                  

3. Basic function code realization

           The basic functions include three points:

           1. Add a new element to the heap, first insert the element to the last position, and then continue to compare with the parent node until the position is no longer changed

           2. Pop the top element of the heap, put the last bit in the first position after popping, and keep comparing it with the child nodes until the position no longer changes.

           3. Priority queue: Turning an array into a heap actually means inserting each element into an empty heap and sorting by priority.

#-*- coding:utf-8 -*-
#实现一个最大堆
#1.使用数组来存放元素
#2.两个核心 方法 shift_up(将元素和父节点比较,如果顺序不对就更换位置) 
#shift_down (将元素和子节点比较,如果顺序不对就更换位置)
#3.添加元素 加入到最后面  然后进行 shift_up(-1)进行堆顺序调整
#4.取出元素 弹出第一个  将最后一个放在第一的位置  然后shift_down(0)进行堆顺序调整
class MaxHeap(object):
    #双下划线表示私有 外部不可以访问 子类也不可以
    # 单下划线表示半私有 外部可以访问 子类可以访问
    def __init__(self):
        self.array=[] #用数组来存放元素
    def _parent(self,index):
        return int((index-1)/2)
    def _leftchild(self,index):
        return int(index*2+1)
    def _rightchild(self,index):
        return int(index*2+2)
    def get_size(self):
        return len(self.array)
    # 将每一个元素和父节点进行比较,如果大于父节点的值则进行位置交换
    def shift_up(self,K):
        parent = self._parent(K)
        if K>0 and self.array[K]>self.array[parent]:
            self.array[K],self.array[parent]=self.array[parent],self.array[K]
            self.shift_up(parent)
    #将节点和自己的子节点比较,如果子节点大于父节点则调换位置
    def shift_down(self,K):
        left_child = self._leftchild(K)
        right_child = self._rightchild(K)
        array_size = self.get_size()
        max_position = K
        if left_child+1<array_size and self.array[max_position] < self.array[left_child]:
            max_position = left_child
        if right_child+1 < array_size and self.array[max_position] < self.array[right_child]:
            max_position = right_child
        if max_position != K:
            self.array[max_position], self.array[K] = self.array[K], self.array[max_position]
            self.shift_down(max_position)
    #将一个元素插入堆,添加到最后一位,然后执行shift_up
    def push(self,V):
        self.array.append(V)
        self.shift_up(len(self.array)-1)
    #删除元素,顶部弹出,将最后一个元素放入顶部,执行shift_down
    def pop(self):
        max_value = self.array[0]
        self.array[0],self.array[len(self.array)-1] = self.array[len(self.array)-1],self.array[0]
        self.array.pop(-1)
        self.shift_down(0)
        return max_value
    #查看堆顶元素
    def find_max(self):
        return self.array[0]
    #将一个数组进行堆化,就是将元素一个个插入堆中
    def heapify(self,arr):
        for i in arr:
            self.push(i)
        return self.array
    #遍历堆
    def listHeap(self):
        return self.array
array = [1,2,3,4,17,6,7,8,9,10]
maxHeap = MaxHeap()
print(maxHeap.heapify(array))
print(maxHeap.pop())
maxHeap.push(15)
print(maxHeap.listHeap())

 4. Heap application

  1. Heap sort

         The idea of ​​heap sort is to heap up a set of data, and then pop the top elements of the heap one by one. The overall complexity is O(nlogn)!

    def heap_sort(self,data):
        self.heapify(data)
        heap_sort = []
        for i in self.array:
            heap_sort.append(i)
        return heap_sort

    2. Get the top K largest numbers

        In fact, it is consistent with the idea of ​​heap sorting above, but we don't need to sort all elements. Just after the elements are piled up, K times on the top of the pile popping is

    def get_max_k(self,data,K):
        self.heapify(data)
        max_k = []
        for i in range(K):
            max_k.append(self.pop())
        return max_k

5. Summary

       This article introduces the concept of the heap in the data structure, which is not the concept of the heap in the memory management of the operating system. We know that the heap is a complete binary tree. For the largest heap, the value of each node is greater than the value of its child nodes (the opposite of the smallest heap), which ensures that the element at the top of the heap is the largest. For the heap, we generally have two operations: save and fetch. When saving, insert the new value into the last bit, and then continue to stack up. When fetching, the element at the top of the heap is popped, and the last element is placed on the top of the heap, and the heaping operation is continued downward.  

         We noticed that the data in the heap is not ordered, it only conforms that the parent node is greater than the child node, and only the top element of the heap can be used. It can be said to be a relatively rough sequence. But because its requirements are not many, it allows us to insert and delete elements very simply. And because the top element of the heap is always the largest, it allows us to easily implement complicated functions such as heap sorting, priority queue, and top K largest numbers. It can be said that its limitations are also its advantages.

6. Gossip

          People say: "You are a good man, he is a good pig." In the eyes of people, those pigs with delicious meat and large body are good pigs. In the eyes of the pig, those people who are full and have to go to work are simply a bunch of big fools, a group of creatures enslaved from the depths of the bone marrow. Human language is a bit too complicated, so I don’t want to live with the boring English words. Essentially speaking, the complexity of language is directly proportional to the number of lies. If it is just for expressing like, you don't even need language, a hug or a kiss, or a look at the other person will be enough to understand. But if you don’t like it but you want to express it, you can only use language. For pigs, it's much simpler. In their world, there are only hum, hum and hum! This is the most advanced language and the most effective way of expression. Like is hum, dislike is hum, delicious is hum, not delicious is hum. From the perspective of deep learning natural language, human language is the most primitive one-hot code, simple and simple. Look at the language of pigs, how high-level abstraction, how perfect encapsulation, absolutely high cohesion, and completely loosely coupled! Let's talk about the relationship between good people, pigs and language. People's language is the best way to prevent people from knowing the truth, because it is a kind of decoration and disguise, and the truth is absolutely true. Even though many times, we feel that what we think is what we say, but in fact we only find some expressions in language that are closer to our thoughts. Language symbols have become our main way of thinking. Recall carefully that language and logic are the way we think. When you enter a plum grove, you will never pick an apple. There is no truth in the same language. Look at the pig again. No pig has ever been convicted of a rapist, and no pig has been pulled out by his companion and shot. That is to say, in their social definition, there is no concept of bad. This also verifies a famous saying that everyone is Yao and Shun. So there is no good person at all, on the contrary, there is no bad pig at all!

      Sorry, great human language! The reason why I am so negative is because I am going crazy by English words.

        

Super handsome lady

 

 

 

Guess you like

Origin blog.csdn.net/gaobing1993/article/details/108768791