File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ # heapify
2
+ def heapify(arr, n, i):
3
+ largest = i # largest value
4
+ l = 2 * i + 1 # left
5
+ r = 2 * i + 2 # right
6
+ # if left child exists
7
+ if l < n and arr[i] < arr[l]:
8
+ largest = l
9
+ # if right child exits
10
+ if r < n and arr[largest] < arr[r]:
11
+ largest = r
12
+ # root
13
+ if largest != i:
14
+ arr[i],arr[largest] = arr[largest],arr[i] # swap
15
+ # root.
16
+ heapify(arr, n, largest)
17
+ # sort
18
+ def heapSort(arr):
19
+ n = len(arr)
20
+ # maxheap
21
+ for i in range(n, -1, -1):
22
+ heapify(arr, n, i)
23
+ # element extraction
24
+ for i in range(n-1, 0, -1):
25
+ arr[i], arr[0] = arr[0], arr[i] # swap
26
+ heapify(arr, i, 0)
27
+ # main
28
+ arr = [2,5,3,8,6,5,4,7]
29
+ heapSort(arr)
30
+ n = len(arr)
31
+ print ("Sorted array is")
32
+ for i in range(n):
33
+ print (arr[i],end=" ")
You can’t perform that action at this time.
0 commit comments