forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergesort.py
39 lines (31 loc) · 1023 Bytes
/
mergesort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def merge_sort(arr):
if len(arr) <= 1:
return arr
# Split the input array into two halves
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
# Recursively sort each half
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
# Merge the sorted halves
return merge(left_half, right_half)
def merge(left, right):
result = []
left_idx, right_idx = 0, 0
while left_idx < len(left) and right_idx < len(right):
if left[left_idx] < right[right_idx]:
result.append(left[left_idx])
left_idx += 1
else:
result.append(right[right_idx])
right_idx += 1
# Add any remaining elements from both left and right halves
result.extend(left[left_idx:])
result.extend(right[right_idx:])
return result
# Example usage:
if __name__ == "__main__":
input_list = [12, 11, 13, 5, 6, 7]
sorted_list = merge_sort(input_list)
print("Sorted array is:", sorted_list)