forked from nryoung/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.py
More file actions
51 lines (35 loc) · 1018 Bytes
/
heap_sort.py
File metadata and controls
51 lines (35 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
heap_sort.py
Implementation of heap sort on a list and returns a sorted list.
Heap Sort Overview:
-------------------
Uses the max heap data structure implemented in a list.
Time Complexity: O(n log n)
Space Complexity: O(1) Auxiliary
Stable: Yes
Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed.
"""
def max_heapify(seq, i, n):
l = 2 * i + 1
r = 2 * i + 2
if l <= n and seq[l] > seq[i]:
largest = l
else:
largest = i
if r <= n and seq[r] > seq[largest]:
largest = r
if largest != i:
seq[i], seq[largest] = seq[largest], seq[i]
max_heapify(seq, largest, n)
def build_heap(seq):
n = len(seq) - 1
for i in range(n/2, -1, -1):
max_heapify(seq, i, n)
def sort(seq):
build_heap(seq)
heap_size = len(seq) - 1
for x in range(heap_size, 0, -1):
seq[0], seq[x] = seq[x], seq[0]
heap_size = heap_size - 1
max_heapify(seq, 0, heap_size)
return seq