Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,32 +1,30 @@
def merge_sort(num_list):
if len(num_list)>1:
mid = int(len(num_list)/2)
lefthalf = num_list[:mid]
righthalf = num_list[mid:]

merge_sort(lefthalf)
merge_sort(righthalf)

i=0
j=0
k=0

while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
num_list[k]=lefthalf[i]
i=i+1
else:
num_list[k]=righthalf[j]
j=j+1
k=k+1

while i < len(lefthalf):
num_list[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):
num_list[k]=righthalf[j]
j=j+1
k=k+1
return num_list
def merge_sort(numbers: list) -> list:
if len(numbers) < 2:
return numbers

middle_index = len(numbers) // 2
left_half = numbers[:middle_index]
right_half = numbers[middle_index:]

return _merge(merge_sort(left_half), merge_sort(right_half))


def _merge(left: list, right: list) -> list:
merged_list = []
left_index = right_index = 0

while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
merged_list.append(left[left_index])
left_index += 1
else:
merged_list.append(right[right_index])
right_index += 1

for index, numbers in ((left_index, left), (right_index, right)):
while index < len(numbers):
merged_list.append(numbers[index])
index += 1

return merged_list
Comment on lines +12 to +29
Copy link
Author

@LesterKim LesterKim Jul 18, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once students learn about Python classes, they can create a non-public class _ListMerger that contains this function as its public method.