Python implements heap sorting algorithm code

Source: Internet
Author: User
Python implements the heap sorting algorithm code. For more information, see The code is as follows:


#! /Usr/bin/python
Import sys

Def left_child (node ):
Return node * 2 + 1

Def right_child (node ):
Return node * 2 + 2

Def parent (node ):
If (node % 2 ):
Return (I-1)/2
Else:
Return (I-2)/2

Def max_heapify (array, I, heap_size ):
L = left_child (I)
R = right_child (I)

Largest = I
If l Largest = l

If r Largest = r

If largest! = I:
Array [I], array [largest] = array [largest], array [I]
Max_heapify (array, largest, heap_size)

Def build_max_heap (array ):
For I in range (len (array)/2,-1,-1 ):
Max_heapify (array, I, len (array ))


Def heap_sort (array ):
Build_max_heap (array)
For I in range (len (array)-1, 0,-1 ):
Array [0], array [I] = array [I], array [0]
Max_heapify (array, 0, I)


If _ name _ = "_ main __":
Array = [0, 2, 6, 98, 34,-5, 23, 11, 89,100, 7]
Heap_sort (array)

For a in array:
Sys. stdout. write ("% d" %)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.