Skip to content

Commit ace7cf2

Browse files
Merge pull request #720 from nanto88/master
add example of merge sort in python
2 parents f950d99 + 0435702 commit ace7cf2

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Python/MergeSort.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# -*- coding: utf-8 -*-
2+
def merge(left_list, right_list):
3+
sorted_list = []
4+
left_list_index = right_list_index = 0
5+
6+
# We use the list lengths often, so its handy to make variables
7+
left_list_length, right_list_length = len(left_list), len(right_list)
8+
9+
for _ in range(left_list_length + right_list_length):
10+
if left_list_index < left_list_length and right_list_index < right_list_length:
11+
# We check which value from the start of each list is smaller
12+
# If the item at the beginning of the left list is smaller, add it
13+
# to the sorted list
14+
if left_list[left_list_index] <= right_list[right_list_index]:
15+
sorted_list.append(left_list[left_list_index])
16+
left_list_index += 1
17+
# If the item at the beginning of the right list is smaller, add it
18+
# to the sorted list
19+
else:
20+
sorted_list.append(right_list[right_list_index])
21+
right_list_index += 1
22+
23+
# If we've reached the end of the of the left list, add the elements
24+
# from the right list
25+
elif left_list_index == left_list_length:
26+
sorted_list.append(right_list[right_list_index])
27+
right_list_index += 1
28+
# If we've reached the end of the of the right list, add the elements
29+
# from the left list
30+
elif right_list_index == right_list_length:
31+
sorted_list.append(left_list[left_list_index])
32+
left_list_index += 1
33+
34+
return sorted_list
35+
36+
37+
def merge_sort(nums):
38+
# If the list is a single element, return it
39+
if len(nums) <= 1:
40+
return nums
41+
42+
# Use floor division to get midpoint, indices must be integers
43+
mid = len(nums) // 2
44+
45+
# Sort and merge each half
46+
left_list = merge_sort(nums[:mid])
47+
right_list = merge_sort(nums[mid:])
48+
49+
# Merge the sorted lists into a new one
50+
return merge(left_list, right_list)
51+
52+
# time complexity : O(nlog(n))
53+
if __name__ == '__main__':
54+
nums = [210, 24, 60, 300, 180]
55+
sorted_nums = merge_sort(nums)
56+
print(sorted_nums)

0 commit comments

Comments
 (0)