I have atttached the code. It has comments for explanation. If you have any queries, feel free to comment.
Program Screenhots for Indentation Reference:
Sample Output (On a part of file):
Program code to copy:
msort.py:
def mergesort(arr, key=lambda x, y: x < y):
if len(arr) >1:
# Sort halves ito
separate memory
mid = len(arr) //
2
L = arr[:mid]
R = arr[mid:]
mergesort(L, key)
mergesort(R, key)
# Merge L and R back
into arr
i = j = k = 0
## put using the
key
while i < len(L) and
j < len(R):
if key(L[i], R[j]):
# put ith item
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
# Checking if any elements were left
while i <
len(L):
arr[k] = L[i]
i+=1
k+=1
while j <
len(R):
arr[k] = R[j]
j+=1
k+=1
ex11a.py:
import msort
def comparator_by_name(x, y):
k = x[1].split() # split to put in tuple
l = y[1].split()
return (k[-1], k[0]) < (l[-1], l[0])
## open the file for reading
lines = []
with open("data.csv", "r") as f:
### read all the lines
for line in f:
## get a line and split
by comma
l =
line.split(',')
## append to lines
lines.append(l)
## sort using the id
# sort by id
with open("data_by_id.txt", "w") as f:
sorted_data = lines.copy() ## make a copy
msort.mergesort(sorted_data, lambda x, y: x[0]
< y[0]) ## use id as the key
for line in sorted_data:
f.write(str(tuple(line))
+ "\n") ## writes the lines
# sort by name
with open("data_by_name.txt", "w") as f:
sorted_name = lines.copy() ## make a copy
msort.mergesort(sorted_name, comparator_by_name)
## use tuple as the comparator
for line in sorted_name:
f.write(str(tuple(line))
+ "\n") ## writes the lines
In Python! Search Exercise 11.A: Mergesort with a Comparator CS 1410 Background The sort algorithms we...