|
| 1 | + |
| 2 | +#made by SHASHANK CHAKRAWARTY |
| 3 | +#Time complexity of above iterative function is Θ(nLogn) |
| 4 | +# Iterative Merge sort (Bottom Up) |
| 5 | + |
| 6 | +# Iterative mergesort function to |
| 7 | +# sort arr[0...n-1] |
| 8 | +def mergeSort(a): |
| 9 | + |
| 10 | + current_size = 1 |
| 11 | + |
| 12 | + # Outer loop for traversing Each |
| 13 | + # sub array of current_size |
| 14 | + while current_size < len(a) - 1: |
| 15 | + |
| 16 | + left = 0 |
| 17 | + # Inner loop for merge call |
| 18 | + # in a sub array |
| 19 | + # Each complete Iteration sorts |
| 20 | + # the iterating sub array |
| 21 | + while left < len(a)-1: |
| 22 | + |
| 23 | + # mid index = left index of |
| 24 | + # sub array + current sub |
| 25 | + # array size - 1 |
| 26 | + mid = left + current_size - 1 |
| 27 | + |
| 28 | + # (False result,True result) |
| 29 | + # [Condition] Can use current_size |
| 30 | + # if 2 * current_size < len(a)-1 |
| 31 | + # else len(a)-1 |
| 32 | + right = ((2 * current_size + left - 1, |
| 33 | + len(a) - 1)[2 * current_size |
| 34 | + + left - 1 > len(a)-1]) |
| 35 | + |
| 36 | + # Merge call for each sub array |
| 37 | + merge(a, left, mid, right) |
| 38 | + left = left + current_size*2 |
| 39 | + |
| 40 | + # Increasing sub array size by |
| 41 | + # multiple of 2 |
| 42 | + current_size = 2 * current_size |
| 43 | + |
| 44 | +# Merge Function |
| 45 | +def merge(a, l, m, r): |
| 46 | +#you create 2 sub arrays with length n1 and n2 |
| 47 | + n1 = m - l + 1 |
| 48 | + n2 = r - m |
| 49 | +#2 arrays are created |
| 50 | + L = [0] * n1 |
| 51 | + R = [0] * n2 |
| 52 | +#copy the elements into the left and right array for sorting |
| 53 | + for i in range(0, n1): |
| 54 | + L[i] = a[l + i] |
| 55 | + for i in range(0, n2): |
| 56 | + R[i] = a[m + i + 1] |
| 57 | +#here it sorts |
| 58 | + i, j, k = 0, 0, l |
| 59 | + while i < n1 and j < n2: |
| 60 | + if L[i] > R[j]: |
| 61 | + a[k] = R[j] |
| 62 | + j += 1 |
| 63 | + else: |
| 64 | + a[k] = L[i] |
| 65 | + i += 1 |
| 66 | + k += 1 |
| 67 | +#and you copy the elements into the arrays i.e Left and Right by comparing it with the size of the array which was declared previously |
| 68 | + while i < n1: |
| 69 | + a[k] = L[i] |
| 70 | + i += 1 |
| 71 | + k += 1 |
| 72 | + |
| 73 | + while j < n2: |
| 74 | + a[k] = R[j] |
| 75 | + j += 1 |
| 76 | + k += 1 |
| 77 | + |
| 78 | + |
| 79 | +# Driver code you can change it accordingly |
| 80 | +a = [12, 11, 13, 5, 6, 7] |
| 81 | +print("Before Sorting ") |
| 82 | +print(a) |
| 83 | + |
| 84 | +mergeSort(a) |
| 85 | + |
| 86 | +print("After Sorting ") |
| 87 | +print(a) |
0 commit comments