From a3058e2428bab24c3cc5cf5021644fb2a0718370 Mon Sep 17 00:00:00 2001 From: Samarth Dad Date: Thu, 22 Oct 2020 09:17:42 +0530 Subject: [PATCH] Merge Sort --- contribution/samarthdad/merge_sort.py | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 contribution/samarthdad/merge_sort.py diff --git a/contribution/samarthdad/merge_sort.py b/contribution/samarthdad/merge_sort.py new file mode 100644 index 00000000..158727db --- /dev/null +++ b/contribution/samarthdad/merge_sort.py @@ -0,0 +1,43 @@ +def mergeSort(myList): + if len(myList) > 1: + mid = len(myList) // 2 + left = myList[:mid] + right = myList[mid:] + + # Recursive call on each half + mergeSort(left) + mergeSort(right) + + # Two iterators for traversing the two halves + i = 0 + j = 0 + + # Iterator for the main list + k = 0 + + while i < len(left) and j < len(right): + if left[i] < right[j]: + # The value from the left half has been used + myList[k] = left[i] + # Move the iterator forward + i += 1 + else: + myList[k] = right[j] + j += 1 + # Move to the next slot + k += 1 + + # For all the remaining values + while i < len(left): + myList[k] = left[i] + i += 1 + k += 1 + + while j < len(right): + myList[k]=right[j] + j += 1 + k += 1 + +myList = [54,26,93,17,77,31,44,55,20] +mergeSort(myList) +print(myList)