Advertisement
asweigart

Untitled

Jun 25th, 2022
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. import timeit, random
  2.  
  3. random.seed(42)
  4.  
  5. left = []
  6. right = []
  7.  
  8. # Create two sorted lists of integers
  9. n = 0
  10. for i in range(100000):
  11. n += random.randint(1, 10)
  12. left.append(n)
  13. n = 0
  14. for i in range(100000):
  15. n += random.randint(1, 10)
  16. right.append(n)
  17.  
  18.  
  19. def merge():
  20. sortedResult = []
  21. iLeft = 0
  22. iRight = 0
  23. while (len(sortedResult) < (len(left) + len(right))):
  24. # Append the smaller of left & right's value to `sortedResult`.
  25. if left[iLeft] < right[iRight]:
  26. sortedResult.append(left[iLeft])
  27. iLeft += 1
  28. else:
  29. sortedResult.append(right[iRight])
  30. iRight += 1
  31.  
  32. # If one of the pointers has reached the end of its list,
  33. # put the rest of the other list into `sortedResult`.
  34. if iLeft == len(left):
  35. sortedResult.extend(right[iRight:])
  36. break
  37. elif iRight == len(right):
  38. sortedResult.extend(left[iLeft:])
  39. break
  40.  
  41.  
  42. def appendAndSort():
  43. sortedResult = left + right
  44. sortedResult.sort()
  45.  
  46.  
  47. timeit.timeit('merge()', globals=globals(), number=10)
  48. timeit.timeit('appendAndSort()', globals=globals(), number=10)
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement