|
| 1 | +# Python program for implementation of MergeSort |
| 2 | + |
| 3 | +# Merges two subarrays of arr[]. |
| 4 | +# First subarray is arr[l..m] |
| 5 | +# Second subarray is arr[m+1..r] |
| 6 | + |
| 7 | + |
| 8 | +def merge(arr, l, m, r): |
| 9 | + n1 = m - l + 1 |
| 10 | + n2 = r - m |
| 11 | + |
| 12 | + # create temp arrays |
| 13 | + L = [0] * (n1) |
| 14 | + R = [0] * (n2) |
| 15 | + |
| 16 | + # Copy data to temp arrays L[] and R[] |
| 17 | + for i in range(0, n1): |
| 18 | + L[i] = arr[l + i] |
| 19 | + |
| 20 | + for j in range(0, n2): |
| 21 | + R[j] = arr[m + 1 + j] |
| 22 | + |
| 23 | + # Merge the temp arrays back into arr[l..r] |
| 24 | + i = 0 # Initial index of first subarray |
| 25 | + j = 0 # Initial index of second subarray |
| 26 | + k = l # Initial index of merged subarray |
| 27 | + |
| 28 | + while i < n1 and j < n2: |
| 29 | + if L[i] <= R[j]: |
| 30 | + arr[k] = L[i] |
| 31 | + i += 1 |
| 32 | + else: |
| 33 | + arr[k] = R[j] |
| 34 | + j += 1 |
| 35 | + k += 1 |
| 36 | + |
| 37 | + # Copy the remaining elements of L[], if there |
| 38 | + # are any |
| 39 | + while i < n1: |
| 40 | + arr[k] = L[i] |
| 41 | + i += 1 |
| 42 | + k += 1 |
| 43 | + |
| 44 | + # Copy the remaining elements of R[], if there |
| 45 | + # are any |
| 46 | + while j < n2: |
| 47 | + arr[k] = R[j] |
| 48 | + j += 1 |
| 49 | + k += 1 |
| 50 | + |
| 51 | +# l is for left index and r is right index of the |
| 52 | +# sub-array of arr to be sorted |
| 53 | + |
| 54 | + |
| 55 | +def mergeSort(arr, l, r): |
| 56 | + if l < r: |
| 57 | + |
| 58 | + # Same as (l+r)//2, but avoids overflow for |
| 59 | + # large l and h |
| 60 | + m = l+(r-l)//2 |
| 61 | + |
| 62 | + # Sort first and second halves |
| 63 | + mergeSort(arr, l, m) |
| 64 | + mergeSort(arr, m+1, r) |
| 65 | + merge(arr, l, m, r) |
| 66 | + |
| 67 | + |
| 68 | +# Driver code to test above |
| 69 | +arr = [12, 11, 13, 5, 6, 7] |
| 70 | +n = len(arr) |
| 71 | +print("Given array is") |
| 72 | +for i in range(n): |
| 73 | + print("%d" % arr[i],end=" ") |
| 74 | + |
| 75 | +mergeSort(arr, 0, n-1) |
| 76 | +print("\n\nSorted array is") |
| 77 | +for i in range(n): |
| 78 | + print("%d" % arr[i],end=" ") |
0 commit comments