How to Implement Merge-Sort

PHOTO EMBED

Tue Jun 18 2024 03:24:52 GMT+0000 (Coordinated Universal Time)

Saved by @pynerds #python

#merge sort

#the merge algorithm
def merge(L1, L2, L):
  i = 0
  j = 0
  while i+j < len(L):
    if j == len(L2) or (i < len(L1) and L1[i] < L2[j]):
       L[i+j] = L1[i]
       i += 1
    else:
       L[i+j] = L2[j]
       j += 1

#main function
def merge_sort(L):

  n = len(L)
  if n < 2:
     return # list is already sorted

  # divide
  mid = n // 2 #midpoint
  L1 = L[0:mid] # the first half
  L2 = L[mid:n] # the second half
 
  # conquer with recursion
  merge_sort(L1) # sort first sub-list
  merge_sort(L2) # sort second sub-list

  # merge result
  merge(L1, L2, L) 

#example
L = [7, 5, 1, 4, 2, 8, 0, 9, 3, 6]
print('Before: ', L)
merge_sort(L)
print('After: ', L)
content_copyCOPY

https://www.pynerds.com/data-structures/implement-merge-sort-in-python/