Home Backend Development Python Tutorial How to implement heap sort algorithm using Python?

How to implement heap sort algorithm using Python?

Sep 19, 2023 am 10:36 AM
python heap sort algorithm

How to implement heap sort algorithm using Python?

How to implement the heap sort algorithm using Python?

Heap sort is a sorting algorithm based on a binary heap, which takes advantage of the properties of a complete binary tree. Heaps can be divided into two types: max heap and min heap. The max heap requires that the value of the parent node is greater than or equal to the value of its child nodes, while the min heap requires that the value of the parent node is less than or equal to the value of its child nodes. In heap sort algorithm we use max heap.

The following are the specific steps and code examples for using Python to implement heap sorting:

Step 1: Build the maximum heap
In the process of building the maximum heap, we need to adjust the heap structure so that The value of each parent node is greater than or equal to the value of its child nodes.

First, we define a function heapify to implement the heap adjustment process. This function accepts three parameters: the heap list heap, the size of the heap, and the index of the parent node to be adjusted.

def heapify(heap, size, parent):
    largest = parent
    left = 2 * parent + 1
    right = 2 * parent + 2

    if left < size and heap[left] > heap[largest]:
        largest = left

    if right < size and heap[right] > heap[largest]:
        largest = right

    if largest != parent:
        heap[parent], heap[largest] = heap[largest], heap[parent]
        heapify(heap, size, largest)
Copy after login

Next, we define a function build_heap to build the maximum heap. This function accepts a list as argument and builds a max-heap based on the elements in the list.

def build_heap(heap):
    size = len(heap)

    for i in range(size // 2 - 1, -1, -1):
        heapify(heap, size, i)
Copy after login

Step 2: Heap sort
After building the maximum heap, we can use the properties of the maximum heap for sorting. The idea of ​​​​heap sorting is to exchange the top element of the heap (maximum value) with the last element each time, adjust the top of the heap, then take out the maximum value, and adjust again until there is only one element left in the heap.

The following are the specific steps and code examples for sorting using the heap sort algorithm:

def heap_sort(heap):
    size = len(heap)

    build_heap(heap)

    for i in range(size - 1, 0, -1):
        heap[0], heap[i] = heap[i], heap[0]
        heapify(heap, i, 0)
Copy after login

Step 3: Test the code
Now, we can use some test data to verify that our code correct.

if __name__ == "__main__":
    # 测试数据
    data = [4, 10, 3, 5, 1]

    heap_sort(data)

    print("排序结果:", data)
Copy after login

Run the above code, the output result is: sorting result: [1, 3, 4, 5, 10], indicating that the heap sort algorithm is correct.

Summary:
Heap sort is an efficient sorting algorithm with a time complexity of O(nlogn). Taking advantage of the complete binary tree properties of the heap, we can achieve this by building a maximum heap and performing heap sorting. Using the Python language, we can implement the heap sort algorithm by writing the heap adjustment function (heapify), the maximum heap building function (build_heap), and the heap sort function (heap_sort). Test code helps us verify that our implementation is correct.

The above is the detailed content of How to implement heap sort algorithm using Python?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles