Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. def merge_and_count(x, y, result, count):
  2. i, j = 0, 0
  3.  
  4. while i < len(x) and j < len(y):
  5. if x[i] > y[j]:
  6. result.append(y[j])
  7. j += 1
  8. count += 1
  9. else:
  10. result.append(x[i])
  11. i += 1
  12.  
  13. result += x[i:]
  14. result += y[j:]
  15.  
  16. return result, count
  17.  
  18. def sort_and_count(array):
  19. if len(array) == 1:
  20. return array, 0
  21.  
  22. count = 0
  23. result = []
  24.  
  25. mid = len(array)//2
  26.  
  27. x = array[:mid]
  28. y = array[mid:]
  29.  
  30. x, c1 = sort_and_count(x)
  31. y, c2 = sort_and_count(y)
  32.  
  33. result, c3 = merge_and_count(x, y, result, count)
  34.  
  35. return result, (c1+c2+c3)
  36.  
  37. def main():
  38. array = [1,3,5,2,4,6]
  39. result, count = sort_and_count(array)
  40. print("there are", count, "split inversion")
  41. print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement