Python Program for Merge Sort

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given an array, we need to sort it using the concept of merge sort

Here we place the maximum element at the end. This is repeated until the array is sorted.

Now let’s observe the solution in the implementation below −

Example

#merge function
def merge(arr, l, m, r):
   n1 = m - l + 1
   n2 = r- m
   # create arrays
   L = [0] * (n1)
   R = [0] * (n2)
   # Copy data to arrays
   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 # first half of array
   j = 0 # second half of array
   k = l # merges two halves
   while i 

Output

Sorted array is
2 3 4 5 5 6 7 8

All the variables are declared in the local scope and their references are seen in the figure above.

Conclusion

In this article, we have learned about how we can make a Python Program for Merge Sort

Updated on: 2019-12-20T06:33:27+05:30

783 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements