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
57 changes: 57 additions & 0 deletions Sorting/merge_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""

Sorting a list of numbers with merge sort algorithm.

"""


def merge_sort(array, left_index, right_index):
if left_index >= right_index:
return

middle = (left_index + right_index)//2
merge_sort(array, left_index, middle)
merge_sort(array, middle + 1, right_index)
merge(array, left_index, right_index, middle)


def merge(array, left_index, right_index, middle):
left_copy = array[left_index:middle + 1]
right_copy = array[middle+1:right_index+1]


left_copy_index = 0
right_copy_index = 0
sorted_index = left_index


while left_copy_index < len(left_copy) and right_copy_index < len(right_copy):


if left_copy[left_copy_index] <= right_copy[right_copy_index]:
array[sorted_index] = left_copy[left_copy_index]
left_copy_index = left_copy_index + 1
# Opposite from above
else:
array[sorted_index] = right_copy[right_copy_index]
right_copy_index = right_copy_index + 1


sorted_index = sorted_index + 1

while left_copy_index < len(left_copy):
array[sorted_index] = left_copy[left_copy_index]
left_copy_index = left_copy_index + 1
sorted_index = sorted_index + 1

while right_copy_index < len(right_copy):
array[sorted_index] = right_copy[right_copy_index]
right_copy_index = right_copy_index + 1
sorted_index = sorted_index + 1


print("enter the numbers")
arr = list(map(int, input().split(' ')))
merge_sort(arr, 0, len(arr)-1)
print(arr)