Implement HeapSort algorithm Your function must take an Arra
Implement HeapSort algorithm. Your function must take an ArrayList as input and output a sorted ArrayList.
Your input is an array of integer numbers which will be read from a text file called input.txt. The input represents one line (the first line of the text file) of numbers separated with commas. Your output must be a line representing comma separated values of the sorted array printed to the standard output (screen).
Solution
Code:
#heapsort functions
def heapsort(lst):
for start in range(int((len(lst)-2)/2), -1, -1):
moveDown(lst, start, len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
moveDown(lst, 0, end - 1)
return lst
def moveDown(lst, start, end):
root = start
while True:
child = root * 2 + 1
if child > end: break
if child + 1 <= end and lst[child] < lst[child + 1]:
child += 1
if lst[root] < lst[child]:
lst[root], lst[child] = lst[child], lst[root]
root = child
else:
break
#reading input from file
a = open(\"input.txt\",\"r\")
b = a.readline()
l = []
l = b.split(\" \")
#performing heapsort
sorted_l = heapsort(l)
string = \" \".join(sorted_l)
#writing the output to output file
aa = open(\"output.txt\",\"a\")
aa.write(string)
aa.close()
a.close()
