程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

4 Python data structure and algorithm

編輯:Python

Table of Contents

Full binary tree

complete binary tree

heap

Heap down adjustment

The sorting process of the heap

Code Implementation

Time complexity


full binary tree

If the degree of every node in the binary tree is 2 except for the leaf nodes, then the binary tree is called a full binary tree.

Complete Binary Tree

If the last layer of nodes in the binary tree is full, and the nodes of the last layer are distributed from left to right in turn, the binary tree is called a complete binary tree.

heap

1. Must be a complete binary tree
2. Implemented with an array
3. The value of any node is the maximum or minimum value of all nodes in its subtree

  • Big root heap: In a complete binary tree, the maximum value of any subtree is at the root node of this subtree.
  • Small root heap: In a complete binary tree, the minimum value of any subtree is at the root node of this subtree.

The direction of the heapDown adjustment

The left and right subtrees of the node are all heaps, but the binary tree that is not itself a heap can be adjusted downward and eventually become a heap

Sorting of the heapProcess

Count out one by one: 1. Construct the band column into a large top heap. According to the nature of the large top heap, the root node (heap top) of the current heap is the largest element in the sequence; 2. Combine the top element and the lastSwap an element, and then reconstruct the remaining nodes into a large top heap; 3. Repeat step 2, and so on, starting from the first construction of the large top heap, each time we build, we can get the maximum value of a sequence, then put it at the end of the big top pile.

Code Implementation

def sift(li,low,high): #low root node high last nodei=low #i starts to point to the root nodej=2*i+1 #j is the left childtmp=li[low] #The value of the top of the heapwhile j<=high:if j+1<=high and li[j+1]>li[j]:j=j+1if li[j]>tmp:li[i]=li[j]i=jj=2*i+1else:li[i]=tmpbreak;else :li[i]=tmpdef heap_sort(li):n=len(li)for i in range((n-2)//2,-1,-1):sift(li,i,n-1)for i in range(n-1,-1,-1):li[0],li[i]=li[i],li[0]sift(li,0,i-1)li= [i for i in range(10)]import randomrandom.shuffle(li)print(li)heap_sort(li)print(li)

Time complexity

O(nlogn)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved