Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import matplotlib.pyplot as plt
- import time
- import random
- import numpy as np
- #create randomized arrays for the algorithm to sort
- #size of the array is set to 10
- #max is set to 50 as the maximum value of the randomy generated values in the array
- def create_array(size=10,max=50):
- from random import randint
- return [randint(0,max) for _ in range(size)]
- start = time.time()
- step = 0
- def mergeSort(nlist):
- if len(nlist)>1:
- mid = len(nlist)//2 #splitting the list in half
- lefthalf = nlist[:mid]
- righthalf = nlist[mid:]
- global step
- step += 1
- mergeSort(lefthalf)
- mergeSort(righthalf)
- i=j=k=0
- while i < len(lefthalf) and j < len(righthalf):
- step += 1
- if lefthalf[i] < righthalf[j]:
- nlist[k]=lefthalf[i]
- i=i+1
- else:
- nlist[k]=righthalf[j]
- j=j+1
- k=k+1
- while i < len(lefthalf):
- step += 1
- nlist[k]=lefthalf[i]
- i=i+1
- k=k+1
- while j < len(righthalf):
- step += 1
- nlist[k]=righthalf[j]
- j=j+1
- k=k+1
- end = time.time()
- test= create_array()
- print test
- mergeSort(test)
- print (test)
- print(end - start)
- print (step)
Add Comment
Please, Sign In to add comment