Python daily delicious (32)-Python data structure and algorithm heap sorting

Source: Internet
Author: User
ArticleDirectory
    • 1. Select sort
    • 2. Heap sorting
    • 3. Efficiency
1. Select sort

The sorting principle is to first select the smallest number, exchange with the first number, and then switch from the second number to the second number ,......

Def Selection_sort ( Data ):
For I In Range ( Len ( Data ) - 1 ):
Min = Data [ I ]
K = I
For J In Range ( I , Len ( Data )):
If Data [ J ] < Min :
Min = Data [ J ]
K = J
If I <> K :
Data [ I ], Data [ K ] = Data [ K ], Data [ I ]

2. Heap sorting

The heap sorting principle adjusts arrays to heaps, exchanges the heap top element with the last element, removes the last node from the heap, and then adjusts the remaining arrays to heaps, then swap the heap element and the last element ......

Def Heap_adjust ( Data , S , M ):
If 2 * S > M :
Return
Temp = S - 1
If Data [ 2 * S - 1 ] > Data [ Temp ]:
Temp = 2 * S - 1
If 2 * S <= M - 1 And Data [ 2 * S ] > Data [ Temp ]:
Temp = 2 * S
If Temp <> S - 1 :
Data [ S - 1 ], Data [ Temp ] = Data [ Temp ], Data [ S - 1 ]
Heap_adjust ( Data , Temp + 1 , M )
Def Heap_sort ( Data ):
M = Len ( Data ) / 2
For I In Range ( M , 0 , - 1 ):
Heap_adjust ( Data , I , Len ( Data ))
Data [ 0 ], Data [ - 1 ] = Data [ - 1 ], Data [ 0 ]
For N In Range ( Len ( Data ) - 1 , 1 , - 1 ):
Heap_adjust ( Data , 1 , N )
Data [ 0 ], Data [ N - 1 ] = Data [ N - 1 ], Data [ 0 ]

3. Efficiency

The heap sorting efficiency is quite high. The result is as follows:

Selection_sort 0:00:02. 219000
Heap_sort 0:00:00. 157000

 

Python daily delicious series (total)

Python daily delicious (30)-Fast sorting of Python data structures and algorithms

Python daily delicious (31)-insert sorting of Python data structures and algorithms

Python daily delicious (32)-Python data structure and algorithm heap sorting

Python every day (33)-five minutes to understand metaclasses [go]

Python daily delicious (34)-decorators

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.