Без опису

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. def merge(arr, l, m, r):
  2. n1 = m - l + 1
  3. n2 = r - m
  4. # create temp arrays
  5. L = [0] * (n1)
  6. R = [0] * (n2)
  7. # Copy data to temp arrays L[] and R[]
  8. for i in range(0, n1):
  9. L[i] = arr[l + i]
  10. for j in range(0, n2):
  11. R[j] = arr[m + 1 + j]
  12. # Merge the temp arrays back into arr[l..r]
  13. i = 0 # Initial index of first subarray
  14. j = 0 # Initial index of second subarray
  15. k = l # Initial index of merged subarray
  16. while i < n1 and j < n2:
  17. if L[i] <= R[j]:
  18. arr[k] = L[i]
  19. i += 1
  20. else:
  21. arr[k] = R[j]
  22. j += 1
  23. k += 1
  24. # Copy the remaining elements of L[], if there
  25. # are any
  26. while i < n1:
  27. arr[k] = L[i]
  28. i += 1
  29. k += 1
  30. # Copy the remaining elements of R[], if there
  31. # are any
  32. while j < n2:
  33. arr[k] = R[j]
  34. j += 1
  35. k += 1
  36. # l is for left index and r is right index of the
  37. # sub-array of arr to be sorted