forked from pravalika2604/pythonbeginner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapsort.py
More file actions
42 lines (38 loc) · 887 Bytes
/
heapsort.py
File metadata and controls
42 lines (38 loc) · 887 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
res = []
cs = ch =sw= 0
def heapsort(heap):
global res,cs
cs+=1
if len(heap)>1:
n = (len(heap)//2)-1
for i in range(n,-1,-1):
heapify(heap,i)
res.append(heap[0])
heap[0] = heap[len(heap)-1]
heap.pop()
heapsort(heap)
else:
res.append(heap[0])
def heapify(heap,i):
global ch,sw
ch+=1
small = i
l = 2*i+1
r = 2*i+2
if l<len(heap) and heap[l]<heap[small]:
small = l
sw=sw+1
if r<len(heap) and heap[r]<heap[small]:
small = r
sw=sw+1
swap = heap[i]
heap[i] = heap[small]
heap[small] = swap
if small!=i:
heapify(heap,small)
print("Enter the array:")
arr = [int(x) for x in input().split()]
heapsort(arr)
print("The sorted array is :")
print(res)
print("Heapify called {} times and Heapsort called {} times,".format(ch,cs))