summaryrefslogtreecommitdiff
path: root/heap-sort.py
diff options
context:
space:
mode:
authorinternetlandlord <f.fredhenry@gmail.com>2022-10-26 16:50:35 +0000
committerinternetlandlord <f.fredhenry@gmail.com>2022-10-26 16:50:35 +0000
commitff55f26f024ff6eaa72b25239906768872bb94ff (patch)
tree8a462252cf7de0c35626404bcc81b14420c963fa /heap-sort.py
parentc63df88afb86cab2de9a22d22030c8687cb25f83 (diff)
Added a heap-sort algorithm, as well as updating README.md accordingly
Diffstat (limited to 'heap-sort.py')
-rwxr-xr-xheap-sort.py63
1 files changed, 63 insertions, 0 deletions
diff --git a/heap-sort.py b/heap-sort.py
new file mode 100755
index 0000000..c8a45eb
--- /dev/null
+++ b/heap-sort.py
@@ -0,0 +1,63 @@
+#!/bin/python3
+
+# ---------- Heap Sort Algorithm
+#
+
+
+# ---------- Imported modules
+import inputoutput as io
+import csv
+import sys
+
+
+# ---------- Main
+target = sys.argv[1]
+
+# ingress of data
+numdata = io.ingressCSV(target)
+
+
+# Heap function (set up for algorithm)
+def heapMake(data, node, root):
+
+ # create root and define left and right tree branches
+ maxi = root
+ left = 2 * root + 1
+ rite = 2 * root + 2
+
+ # check for existence of left child and if so, compare to root
+ if left < node and data[maxi] < data[left]:
+ maxi = left
+
+ # check for existence of right child and if so, compare to root
+ if rite < node and data[maxi] < data[rite]:
+ maxi = rite
+
+ # if needed change out root value using a swap assignment
+ if maxi != root:
+ data[root], data[maxi] = data[maxi], data[root]
+
+ # recursively make root into a heap
+ heapMake(data, node, maxi)
+
+
+# Algorithm
+def heapSort(atad):
+ span = len(atad)
+
+ # buildup heap
+ for i in range(span // 2 - 1, -1, -1):
+ heapMake(atad, span, i)
+
+ # extract heap elements single-file
+ for i in range(span - 1, 0, -1):
+ # swap assignment
+ atad[i], atad[0] = atad[0], atad[i]
+ heapMake(atad, i, 0)
+
+# using sorting algorithm
+heapSort(numdata)
+
+# finishing up
+print("Sorting done! Writing to file")
+io.egressCSV(numdata,target)