Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

Python Merge Sort With File Input

This document defines a merge sort algorithm using a merge function to recursively sort lists into sublists of 1 element, then merge the sorted sublists back together. The merge function compares elements in two input lists and appends the smaller element to the result, while the merge_sort function recursively calls itself on left and right halves of the input list until single elements remain before calling merge to combine the sorted sublists.

Uploaded by

Max Zhukousky
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python Merge Sort With File Input

This document defines a merge sort algorithm using a merge function to recursively sort lists into sublists of 1 element, then merge the sorted sublists back together. The merge function compares elements in two input lists and appends the smaller element to the result, while the merge_sort function recursively calls itself on left and right halves of the input list until single elements remain before calling merge to combine the sorted sublists.

Uploaded by

Max Zhukousky
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import sys

def merge(left, right):


result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] > right[j]:
result.append(right[j])
j = j + 1
print(f"result array: {result}")
else:
result.append(left[i])
i = i + 1
print(f"result array: {result}")
while i < len(left):
result.append(left[i])
i = i + 1
while j < len(right):
result.append(right[j])
j = j + 1
return result

def merge_sort(l):
if len(l) < 2:
return l[:] # return the copy of the list back if there is only one
element
else:
middle = int(len(l) / 2) # integer value
left = merge_sort(l[:middle]) # left half
right = merge_sort(l[middle:]) # right half

return merge(left, right)

def main():
# with open("/home/max/sorts.txt") as f:
with open(sys.argv[1]) as f:
my_list = [int(num) for num in f.readline().split()]
result = merge_sort(my_list)
print(result)

if __name__ == '__main__':
main()

You might also like