Skip to content

Commit 9b9e4cd

Browse files
authored
Merge pull request TheAlgorithms#18 from arijit-pande/master
added implementation for heap sort algorithm
2 parents 45af05b + 7ce559e commit 9b9e4cd

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

sorts/heap_sort.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
from __future__ import print_function
3+
4+
5+
def heapify(unsorted,index,heap_size):
6+
largest = index
7+
left_index = 2*index + 1
8+
right_index = 2*index + 2
9+
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
10+
largest = left_index
11+
12+
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
13+
largest = right_index
14+
15+
if largest != index:
16+
unsorted[largest],unsorted[index] = unsorted[index],unsorted[largest]
17+
heapify(unsorted,largest,heap_size)
18+
19+
def heap_sort(unsorted):
20+
n=len(unsorted)
21+
for i in range (n/2 - 1 , -1, -1) :
22+
heapify(unsorted,i,n)
23+
for i in range(n - 1, -1, -1):
24+
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
25+
heapify(unsorted,0,i)
26+
return unsorted
27+
28+
29+
if __name__ == '__main__':
30+
import sys
31+
if sys.version_info.major < 3:
32+
input_function = raw_input
33+
else:
34+
input_function = input
35+
36+
user_input = input_function('Enter numbers separated by coma:\n')
37+
unsorted = [int(item) for item in user_input.split(',')]
38+
print (heap_sort(unsorted))
39+

0 commit comments

Comments
 (0)