Skip to content

Commit b3f6fc9

Browse files
author
Pragati Gupta
committed
merge
1 parent 17c4258 commit b3f6fc9

File tree

1 file changed

+42
-3
lines changed

1 file changed

+42
-3
lines changed
Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,65 @@
1+
# 📌 Merge Sort Algorithm
2+
# Language: Python
3+
# Category: Sorting
4+
# Time Complexity: O(n log n)
5+
# Space Complexity: O(n)
6+
7+
"""
8+
Merge Sort is a classic Divide and Conquer algorithm.
9+
It works in three main steps:
10+
1. Divide: Split the array into two halves.
11+
2. Conquer: Recursively sort the two halves.
12+
3. Combine: Merge the two sorted halves into a single sorted array.
13+
"""
14+
115
def merge_sort(arr):
16+
"""
17+
Sorts the input list 'arr' using the Merge Sort algorithm.
18+
:param arr: list of elements (int/float) to be sorted
19+
:return: sorted list
20+
"""
21+
# Base condition: if array has 0 or 1 elements, it's already sorted
222
if len(arr) <= 1:
323
return arr
24+
25+
# Step 1: Divide the array into two halves
426
mid = len(arr) // 2
527
left_half = merge_sort(arr[:mid])
628
right_half = merge_sort(arr[mid:])
29+
30+
# Step 2: Merge the sorted halves
731
return merge(left_half, right_half)
832

33+
934
def merge(left, right):
35+
"""
36+
Merges two sorted lists 'left' and 'right' into a single sorted list.
37+
:param left: sorted list
38+
:param right: sorted list
39+
:return: merged sorted list
40+
"""
1041
merged = []
1142
i = j = 0
43+
44+
# Compare elements of both halves and add the smaller one
1245
while i < len(left) and j < len(right):
1346
if left[i] <= right[j]:
1447
merged.append(left[i])
1548
i += 1
1649
else:
1750
merged.append(right[j])
1851
j += 1
52+
53+
# If there are remaining elements in left or right, add them
1954
merged.extend(left[i:])
2055
merged.extend(right[j:])
56+
2157
return merged
2258

59+
60+
# 🧪 Example usage
2361
if __name__ == "__main__":
24-
arr = list(map(int, input("Enter numbers separated by space: ").split()))
25-
sorted_arr = merge_sort(arr)
26-
print("Sorted array:", sorted_arr)
62+
sample_array = [38, 27, 43, 3, 9, 82, 10]
63+
print("Original array:", sample_array)
64+
sorted_array = merge_sort(sample_array)
65+
print("Sorted array:", sorted_array)

0 commit comments

Comments
 (0)