Concept and code of implementing heap sort algorithm in Python

WBOY
Release: 2024-01-22 19:39:05
forward
894 people have browsed it

堆排序算法概念 Python实现堆排序算法

The prerequisite for understanding the heap sort algorithm is to know the complete binary tree and heap data structure. The heap sort algorithm visualizes the array as a complete binary tree, so it is also called a "heap".

Heap sorting algorithm principle

1. According to the maximum heap attribute, the largest item in the data group is stored in the root node

2. Remove the root element and place it at the end of the array (nth position), put the last item of the tree into the vacant position.

3. Reduce the heap size by 1.

4. Heap the root element again

5. Repeat the process until all items in the list are sorted

Python implements heap sorting algorithm

指定数组arr= 1 12 9 5 6 10

def heapify(arr, n, i):
      largest = i
      l = 2 * i + 1
      r = 2 * i + 2
  
      if l < n and arr[i] < arr[l]:
          largest = l
  
      if r < n and arr[largest] < arr[r]:
          largest = r
  
heapifying
      if largest != i:
          arr[i], arr[largest] = arr[largest], arr[i]
          heapify(arr, n, largest)
  
def heapSort(arr):
      n = len(arr)
  
      for i in range(n//2, -1, -1):
          heapify(arr, n, i)
  
      for i in range(n-1, 0, -1):
          arr[i], arr[0] = arr[0], arr[i]
  
          heapify(arr, i, 0)
  
  arr = [1, 12, 9, 5, 6, 10]
  heapSort(arr)
  n = len(arr)
  print("Sorted array is")
  for i in range(n):
      print("%d " % arr[i], end=&#x27;&#x27;)
Copy after login

The above is the detailed content of Concept and code of implementing heap sort algorithm in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:163.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!