From 798c764c529d45da52fdb499fdba6e3065fee1cd Mon Sep 17 00:00:00 2001 From: CO17324 <36540235+CO17324@users.noreply.github.com> Date: Thu, 29 Oct 2020 00:02:52 +0530 Subject: [PATCH] Added merge sort --- merge_sort | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 merge_sort diff --git a/merge_sort b/merge_sort new file mode 100644 index 0000000..93b9770 --- /dev/null +++ b/merge_sort @@ -0,0 +1,53 @@ +def merge_list(arr, l, m, r): + n1 = m - l + 1 + n2 = r- m + L = [0] * (n1) + R = [0] * (n2) + + for i in range(0 , n1): + L[i] = arr[l + i] + + for j in range(0 , n2): + R[j] = arr[m + 1 + j] + + i = 0 # Initial index of first subarray + j = 0 # Initial index of second subarray + k = l # Initial index of merged subarray + + while i < n1 and j < n2 : + if L[i] <= R[j]: + arr[k] = L[i] + i += 1 + else: + arr[k] = R[j] + j += 1 + k += 1 + + while i < n1: + arr[k] = L[i] + i += 1 + k += 1 + + while j < n2: + arr[k] = R[j] + j += 1 + k += 1 + +def mergeSort(arr,l,r): + if l < r: + m = (l+(r-1))//2 + mergeSort(arr, l, m) + mergeSort(arr, m+1, r) + merge_list(arr, l, m, r) + +arr = [12, 11, 13, 5, 6, 7] +n = len(arr) +print ("Given array is") +for i in range(n): + print ("%d" %arr[i]), + +mergeSort(arr,0,n-1) +print ("\n\nSorted array is") +for i in range(n): + print ("%d" %arr[i]), +