Talilo

MergeSort.py

Mar 16th, 2023 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. # MergeSort in Python
  2.  
  3.  
  4. def mergeSort(array):
  5.     if len(array) > 1:
  6.  
  7.         #  r is the point where the array is divided into two subarrays
  8.         r = len(array)//2
  9.         L = array[:r]
  10.         M = array[r:]
  11.  
  12.         # Sort the two halves
  13.         mergeSort(L)
  14.         mergeSort(M)
  15.  
  16.         i = j = k = 0
  17.  
  18.         # Until we reach either end of either L or M, pick larger among
  19.         # elements L and M and place them in the correct position at A[p..r]
  20.         while i < len(L) and j < len(M):
  21.             if L[i] < M[j]:
  22.                 array[k] = L[i]
  23.                 i += 1
  24.             else:
  25.                 array[k] = M[j]
  26.                 j += 1
  27.             k += 1
  28.  
  29.         # When we run out of elements in either L or M,
  30.         # pick up the remaining elements and put in A[p..r]
  31.         while i < len(L):
  32.             array[k] = L[i]
  33.             i += 1
  34.             k += 1
  35.  
  36.         while j < len(M):
  37.             array[k] = M[j]
  38.             j += 1
  39.             k += 1
  40.  
  41.  
  42. # Print the array
  43. def printList(array):
  44.     for i in range(len(array)):
  45.         print(array[i], end=" ")
  46.     print()
  47.  
  48.  
  49. # Driver program
  50. if __name__ == '__main__':
  51.     array = [6, 5, 12, 10, 9, 1]
  52.  
  53.     mergeSort(array)
  54.  
  55.     print("Sorted array is: ")
  56.     printList(array)
Add Comment
Please, Sign In to add comment