Python heap sorting algorithm instance code

Source: Internet
Author: User
Python implementation heap sorting algorithm code, the need for friends can refer to the following

The code is as follows:

#!/usr/bin/python import sys def left_child (node): Return node * 2 + 1 def right_c Hild (node): Return node * 2 + 2 def Parent (node): if (node% 2): return (i-1)/2 Else:return (i-2)/2 def MAX_HEAPI FY (array, I, heap_size): L = left_child (i) r = right_child (i) largest = i if L < heap_size and array[l] > Array[i]: largest = L if R < Heap_size and Array[r] > Array[largest]: 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, One, 7] Heap_sort (array) for a in Array:sys.stdout.write ("%d"% a) 

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.