Guest User

Untitled

a guest
Jan 23rd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. # First subarray is arr[l..m]
  2. # Second subarray is arr[m+1..r]
  3. def merge(arr, l, middle, r):
  4. leftlength = middle - l + 1
  5. rightlength = r - middle
  6.  
  7. # create temporary arrays
  8. left = []
  9. right = []
  10.  
  11. # Copy data to temp subarrays L[] and R[]
  12. for i in range(leftlength):
  13. left.append(arr[l + i])
  14.  
  15. for j in range(rightlength):
  16. right.append(arr[middle + 1 + j])
  17.  
  18. i = 0 # Initial index of left subarray
  19. j = 0 # Initial index of right subarray
  20. k = l # Initial index of main array
  21. # Merge the subarrays into arr[l..r]
  22. while i < leftlength and j < rightlength :
  23. if left[i] <= right[j] :
  24. arr[k] = left[i]
  25. i += 1
  26. else:
  27. arr[k] = right[j]
  28. j += 1
  29. k += 1
  30.  
  31. # Copy the rest of left array if it remains
  32. while i < leftlength:
  33. arr[k] = left[i]
  34. i += 1
  35. k += 1
  36.  
  37. #Copy the rest of the right array if it remains
  38. while j < rightlength:
  39. arr[k] = right[j]
  40. j += 1
  41. k += 1
  42.  
  43. # l is for left index and r is right index of the subject array to be sorted
  44. def mergeSort(arr,l,r):
  45. if l < r: #need this if statement because it allows to stop when array length is 1
  46. middle = (l+r)//2
  47.  
  48. mergeSort(arr, l, middle)
  49. mergeSort(arr, middle+1, r)
  50. merge(arr, l, middle, r)
  51.  
  52.  
  53.  
  54. #TEST
  55. import random
  56. arr = [int(100*random.random()) for i in range(100)]
  57. n = len(arr)
  58. print ("Generated: ", arr)
  59. mergeSort(arr,0,n-1)
  60. print ("\nSorted: ", arr)
  61.  
  62. #I could not figure out how to keep count of the steps in merge sort; each time a function calls itself,
  63. #it resets the count. But without setting an initial value in the function, it can't add the counts.
Add Comment
Please, Sign In to add comment