TShiva

merge_sort

Jul 18th, 2016
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. # import random
  2. arr = [9, 1, 4, 45, 16, 64, 37, 34, 45, 65, 76]
  3.  
  4.  
  5. # for 0 in 100:
  6.  
  7. # arr.append(random.randint(1,100))
  8.  
  9. def merge(left, right, array):
  10.     i, j, k = (0, 0, 0)
  11.     h = len(right)-1
  12.     m = len(left)-1
  13.     while i <= m and j <= h:
  14.         if left[i] < right[j]:
  15.             array[k] = left[i]
  16.             k += 1
  17.             i += 1
  18.         else:
  19.             array[k] = right[j]
  20.             k += 1
  21.             j += 1
  22.     while i <= m:
  23.         array[k] = left[i]
  24.         k += 1
  25.         i += 1
  26.     while j <= h:
  27.         array[k] = right[j]
  28.         k += 1
  29.         j += 1
  30.  
  31.  
  32.  
  33. def merge_sort(array):
  34.     n = len(array)
  35.     if n < 2:
  36.         return n
  37.     if n >= 2:
  38.         m = int(n / 2)
  39.         left = array[:m]
  40.         right = array[m:]
  41.         merge_sort(left)
  42.         merge_sort(right)
  43.         merge(left, right, array)
  44.  
  45. merge_sort(arr)
  46. print(arr)
Add Comment
Please, Sign In to add comment