|
@@ -0,0 +1,53 @@
|
|
1
|
+# Luis Andrés López Mañán
|
|
2
|
+# Program written by hand as a draft on 09/19/2022
|
|
3
|
+# Credit goes to GeeksForGeeks
|
|
4
|
+# Link: https://www.geeksforgeeks.org/python-program-for-heap-sort/
|
|
5
|
+# Last access on 09/19/2022
|
|
6
|
+# Program wrriten and edited on 10/10/2022
|
|
7
|
+
|
|
8
|
+# This function heapifies a subtree rooted at an index
|
|
9
|
+# i. Also, n is the size of a heap and arr is array.
|
|
10
|
+
|
|
11
|
+def heapify (arr, n, i):
|
|
12
|
+ # largest is root for now
|
|
13
|
+ largest = i
|
|
14
|
+
|
|
15
|
+ # left child of root
|
|
16
|
+ left = 2 * i + 1
|
|
17
|
+
|
|
18
|
+ # right child of root
|
|
19
|
+ right = 2 * i + 2
|
|
20
|
+
|
|
21
|
+ # Checks if root has a left child and is greater
|
|
22
|
+ # than root
|
|
23
|
+ if l < n and arr[i] < arr[l] :
|
|
24
|
+ largest = l
|
|
25
|
+
|
|
26
|
+ # Checks if root has a right child and is greater
|
|
27
|
+ # than root
|
|
28
|
+ if r < n and arr[largest] < arr[r]:
|
|
29
|
+ largest = r
|
|
30
|
+
|
|
31
|
+ # If necessary, this changes root by swapping va-
|
|
32
|
+ # lues
|
|
33
|
+ arr[i], arr[largest] = arr[largest], arr[i]
|
|
34
|
+
|
|
35
|
+ # This heapifies the root repeatedly
|
|
36
|
+ heapify(arr, n, largest)
|
|
37
|
+
|
|
38
|
+# This function sorts an array of a given size n
|
|
39
|
+def heapSort(arr, n):
|
|
40
|
+ # A max heap is built and last parent will be at
|
|
41
|
+ # position number h1, i.e., half the given size of
|
|
42
|
+ # and array. Therefore, that will be the starting
|
|
43
|
+ # location.
|
|
44
|
+ h1 = n // 2 - 1
|
|
45
|
+ for i in range(h1, -1, -1):
|
|
46
|
+ heapify(arr, n, i)
|
|
47
|
+
|
|
48
|
+ # This extracts elements one by one.
|
|
49
|
+ for i in range(n - 1, 0, -1):
|
|
50
|
+ # Swaps, then heapifies
|
|
51
|
+ arr[i], arr[0] = arr[0], arr[i]
|
|
52
|
+ heapify(arr, i, 0)
|
|
53
|
+
|