Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 3ff8965

Browse files
Update MergeSort.py (#927)
Remove the self parameter from both the merge() and mergeSort() functions as they are not instance methods of the class. Rename the arr parameter in the mergeSort() function to unsorted_list or something similar to make it more descriptive. Add type hints to the function parameters and return values to improve code readability and maintainability. Update the docstring of the mergeSort() function to adhere to the Python docstring conventions. Note: I assumed that the input list contains only integers. If the list can contain any type of elements, you may need to modify the code accordingly. Signed-off-by: NIKITA PANDEY <113332472+nikitapandeyy@users.noreply.github.com>
1 parent 5e2086b commit 3ff8965

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

Python/Algorithms/DivideAndConquer/MergeSort.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,16 @@
1-
def merge(self, left, right):
1+
from typing import List
2+
3+
4+
def merge(left: List[int], right: List[int]) -> List[int]:
5+
"""Merges two sorted lists into a single sorted list.
6+
7+
Args:
8+
left (list): The left half of the list to be merged.
9+
right (list): The right half of the list to be merged.
10+
11+
Returns:
12+
list: The sorted list resulting from merging the left and right halves.
13+
"""
214
if len(left) == 0:
315
return right
416

@@ -26,23 +38,20 @@ def merge(self, left, right):
2638
return result
2739

2840

29-
def mergeSort(self, arr):
30-
""" mergeSort Algorithm Implementation in Python 3
41+
def merge_sort(unsorted_list: List[int]) -> List[int]:
42+
"""Sorts a list of integers using the merge sort algorithm.
3143
32-
arr : Unorded list
33-
output : Return list in ascending order.
34-
time complexity : O(n log2n)
35-
Note : O(n log2n) is the best possible worst-case runtime that can be
36-
achieved by a sorting algorithm.
44+
Args:
45+
unsorted_list (list): The unsorted list to be sorted.
3746
38-
Example :
39-
>>> mergeSort([4,2,6,5,9,8])
40-
[2, 4, 5, 6, 8, 9]"""
47+
Returns:
48+
list: The sorted list.
49+
"""
50+
if len(unsorted_list) < 2:
51+
return unsorted_list
4152

42-
if len(arr) < 2:
43-
return arr
53+
midpoint = len(unsorted_list) // 2
4454

45-
midpoint = len(arr) // 2
55+
return merge(left=merge_sort(unsorted_list[:midpoint]),
56+
right=merge_sort(unsorted_list[midpoint:]))
4657

47-
return merge(left=mergeSort(arr[:midpoint]),
48-
right=mergeSort(arr[midpoint:]))

0 commit comments

Comments
 (0)