Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Heap Sort

Python Heap Sort

Document Object Reference Manual Python3 Examples

Heap sort is a sorting algorithm designed using the heap data structure. A heap is an approximately complete binary tree structure that satisfies the heap property: the key (or index) of a child node is always less than (or greater than) that of its parent node. Heap sort can be described as a selection sort that uses the heap concept to sort.

Example

def

heapify

(

arr

,

n

,

i

)

:

largest

=

i

l

=

2

i

1

left = 2*i + 1

r

=

2

i

2

right = 2*i + 2

if

l

<

n

and

arr

[

i

]

<

arr

[

l

]

:

largest

=

l

if

r

<

n

and

arr

[

largest

]

<

arr

[

r

]

:

largest

=

r

if

largest

!=

i

:

arr

[

i

]

,

arr

[

largest

]

=

arr

[

largest

]

,

arr

[

i

]

Swap

heapify

(

arr

,

n

,

largest

)

def

heapSort

(

arr

)

:

n

=

len

(

arr

)

Build a maxheap.

for

i

in

range

(

n

, -

1

, -

1

)

:

heapify

(

arr

,

n

,

i

)

Swap elements one by one

for

i

in

range

(

n

1

,

0

, -

1

)

:

arr

[

i

]

,

arr

[

0

]

=

arr

[

0

]

,

arr

[

i

]

Swap

heapify

(

arr

,

i

,

0

)

arr

=

[

12

,

11

,

13

,

5

,

6

,

7

]

heapSort

(

arr

)

n

=

len

(

arr

)

print

(

"

After sorting

"

)

for

i

in

range

(

n

)

:

print

(

"

%d

"

%

arr

[

i

]

)

,

The output of the code above is:


排序后
5
6
7
11
12
13

Document Object Reference Manual Python3 Examples