Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import timeit, random
- random.seed(42)
- left = []
- right = []
- # Create two sorted lists of integers
- n = 0
- for i in range(100000):
- n += random.randint(1, 10)
- left.append(n)
- n = 0
- for i in range(100000):
- n += random.randint(1, 10)
- right.append(n)
- def merge():
- sortedResult = []
- iLeft = 0
- iRight = 0
- while (len(sortedResult) < (len(left) + len(right))):
- # Append the smaller of left & right's value to `sortedResult`.
- if left[iLeft] < right[iRight]:
- sortedResult.append(left[iLeft])
- iLeft += 1
- else:
- sortedResult.append(right[iRight])
- iRight += 1
- # If one of the pointers has reached the end of its list,
- # put the rest of the other list into `sortedResult`.
- if iLeft == len(left):
- sortedResult.extend(right[iRight:])
- break
- elif iRight == len(right):
- sortedResult.extend(left[iLeft:])
- break
- def appendAndSort():
- sortedResult = left + right
- sortedResult.sort()
- timeit.timeit('merge()', globals=globals(), number=10)
- timeit.timeit('appendAndSort()', globals=globals(), number=10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement