0% found this document useful (0 votes)
7 views2 pages

Python Merge Sort Implementation

Uploaded by

KUNAL SARDANA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Python Merge Sort Implementation

Uploaded by

KUNAL SARDANA
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program-4

Aim: Write a program to implement Merge Sort in python.


def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

left_sorted = merge_sort(left_half)
right_sorted = merge_sort(right_half)

return merge(left_sorted, right_sorted)

def merge(left, right):


merged_list = []
i=j=0

while i < len(left) and j < len(right):


if left[i] < right[j]:
merged_list.append(left[i])
i += 1
else:
merged_list.append(right[j])
j += 1

merged_list.extend(left[i:])
merged_list.extend(right[j:])

return merged_list

data = [38, 27, 43, 3, 9, 82, 10]


sorted_data = merge_sort(data)
print(sorted_data)
Output:

You might also like