nathanwailes

Divide and Conquer

Mar 26th, 2024 (edited)
790
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. """
  2. This algorithm divides the original problem into smaller sub-problems, solves the sub-problems recursively, and combines their solutions to get the solution to the original problem.
  3.  
  4. Pseudocode:
  5.  
  6. # divide and conquer - takes an array/subarray
  7.    # handle the base case w/ 0 or 1 elements (no dividing-and-conquering/recursion needed)
  8.    # recursively handle left and right halves
  9.    # merge them:
  10.    # handle the case whether either half could be next
  11.    # add any remainder from either half
  12. """
  13.  
  14. def merge_sort(arr):
  15.     # edge case: handle the edge case where the list is too short to need processing
  16.     if len(arr) <= 1:
  17.         return
  18.    
  19.     # recurse: recursively call this function on the left and right halves of the list
  20.     middle = len(arr) // 2
  21.     L = arr[:middle]
  22.     R = arr[middle:]
  23.     merge_sort(L)
  24.     merge_sort(R)
  25.    
  26.     # merge: merge the two sorted halves
  27.     # first handle the case where either of the two halves could have the next element
  28.     l = r = a = 0
  29.     while l < len(L) and r < len(R):
  30.         if L[l] < R[r]:
  31.             arr[a] = L[l]
  32.             l += 1
  33.         else:
  34.             arr[a] = R[r]
  35.             r += 1
  36.         a += 1
  37.    
  38.     # copy remainder: ...then handle the case where only one half has the next element
  39.     while l < len(L):
  40.         arr[a] = L[l]
  41.         l += 1
  42.         a += 1
  43.     while r < len(R):
  44.         arr[a] = R[r]
  45.         r += 1
  46.         a += 1
  47.  
  48.        
  49. arr = [40, 10, 5, 4, 3]
  50. merge_sort(arr)
  51. print(arr)
Advertisement
Add Comment
Please, Sign In to add comment