0% found this document useful (0 votes)
34 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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 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
We take content rights seriously. If you suspect this is your content, claim it here.
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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy