Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bb97a1e

Browse files
Add Python
1 parent e832ece commit bb97a1e

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

‎7.heapSort.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,38 @@ function heapSort(arr) {
7171
}
7272
return arr;
7373
}
74-
```
74+
```
75+
## 4. Python 代码实现
76+
77+
```python
78+
def buildMaxHeap(arr):
79+
import math
80+
for i in range(math.floor(len(arr)/2),-1,-1):
81+
heapify(arr,i)
82+
83+
def heapify(arr, i):
84+
left = 2*i+1
85+
right = 2*i+2
86+
largest = i
87+
if left < arrLen and arr[left] > arr[largest]:
88+
largest = left
89+
if right < arrLen and arr[right] > arr[largest]:
90+
largest = right
91+
92+
if largest != i:
93+
swap(arr, i, largest)
94+
heapify(arr, largest)
95+
96+
def swap(arr, i, j):
97+
arr[i], arr[j] = arr[j], arr[i]
98+
99+
def heapSort(arr):
100+
global arrLen
101+
arrLen = len(arr)
102+
buildMaxHeap(arr)
103+
for i in range(len(arr)-1,0,-1):
104+
swap(arr,0,i)
105+
arrLen -=1
106+
heapify(arr, 0)
107+
return arr
108+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /