Heap sort (python)

Source: Internet
Author: User

Heap Sorting algorithm

First look at the first function heapadjust, this function is already the composition of the heap of the two-fork tree, if the node K data changes, the node K is modified to make it a new heap binary tree, n is the data length.

def heapadjust (lst,k,n): While    (2*k+1<n):        j=2*k+1        if J+1<n and lst[j]>lst[j+1]:            j=j+1        If LST[J]<LST[K]:            temp=lst[k]            lst[k]=lst[j]            lst[j]=temp            k=j        else:    break return LST

The Heapsort function, using the first function above, constructs a heap binary tree and uses the above function to sort

def heapsort (LST):    N=len (LST) for    I in range (int (N/2) -1,-1,-1):        lst=heapadjust (lst,i,n)    print (LST) For    i in range (n-1,0,-1):        temp=lst[0]        lst[0]=lst[i]        lst[i]=temp        lst=heapadjust (lst,0,i)    return LST

Test function

A=[1,5,2,8,3,4,6,9,7]print (a) result=heapsort (a) print (result)


Heap sort (python)

Related Article

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.