Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Python question! having issues with my merge sort python program input is an array from data.txt i think i did this part right output needed

Python question!

having issues with my merge sort python program

input is an array from data.txt i think i did this part right

output needed in a file called mergesort.txt can't figure out how to add properly without error?

my code is below and i keep getting an index error i am also trying to pop off the first index value as it only counts the amount of values in my array for example if data.txt is 4, 3, 5, 8, 1 the sorted array would be 1, 3, 5, 8 thanks for the help! The error is at line 37 or del l1[0]

def merge(left, right): if not len(left) or not len(right): return left or right result = [] i, j = 0, 0 while (len(result) < len(left) + len(right)): if left[i] < right[j]: result.append(left[i]) i+= 1 else: result.append(right[j]) j+= 1 if i == len(left) or j == len(right): result.extend(left[i:] or right[j:]) break return result def mergesort(list): if len(list) < 2: return list middle = len(list)/2 left = mergesort(list[:middle]) right = mergesort(list[middle:]) return merge(left, right)

f=open("data.txt","r"); list1=f.readline().split(); list2=f.readline().split(); l1=[] l2=[] for val in list1: l1.append(int(val)) del l1[0] print("Merge Sort"); mergeSort(l1) print(l1)

for val in list2: l2.append(int(val)) del l2[0] mergeSort(l2) print (l2)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions