Skip to content

Instantly share code, notes, and snippets.

@joaofeitoza13
Created February 28, 2018 20:14
Show Gist options
  • Save joaofeitoza13/4f5952825829422b94d0727b8d4a125f to your computer and use it in GitHub Desktop.
Save joaofeitoza13/4f5952825829422b94d0727b8d4a125f to your computer and use it in GitHub Desktop.
Code of mergesort implemented in Python, ploted using matplotlib.
from random import randint
from timeit import timeit
import matplotlib.pyplot as plt
def reverseArray(lenght):
a = []
for i in range(lenght):
a.append(lenght-i)
return a
def randomArray(length):
array = []
tmp = 0
while tmp < length:
num = randint(1, length*10)
if num not in array:
array.append(num)
tmp += 1
return array
def mergeSort(array):
if len(array) > 1:
half = len(array) // 2
lArray = array[:half]
rArray = array[half:]
mergeSort(lArray)
mergeSort(rArray)
lMark, rMark, position = 0, 0, 0
while lMark < len(lArray) and rMark < len(rArray):
if lArray[lMark] < rArray[rMark]:
array[position] = lArray[lMark]
lMark += 1
else:
array[position] = rArray[rMark]
rMark += 1
position += 1
while lMark < len(lArray):
array[position] = lArray[lMark]
lMark += 1
position += 1
while rMark < len(rArray):
array[position] = rArray[rMark]
rMark += 1
position += 1
timeRandom = []
timeReverse = []
lengths = []
elements = [1000, 3000, 6000, 9000, 12000, 15000, 18000, 21000, 24000]
def desenhaGrafico(xl = "Qnt. Elements(und)", yl = "Time(sec)"):
fig = plt.figure(figsize=(10, 8))
plt.title('Mergesort Analysis', fontsize=20)
plt.plot(lengths, timeRandom, label = "Mergesort - Random")
plt.plot(lengths, timeReverse, label = "Mergesort - Reverse")
legend = plt.legend(loc='upper left', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.xlabel(xl)
plt.ylabel(yl)
fig.savefig('graph.png')
def main():
for _tmp in elements:
lengths.append(_tmp)
arrayRandom = randomArray(_tmp)
arrayReverse = reverseArray(_tmp)
timeRandom.append(timeit("mergeSort({})".format(arrayRandom),
setup = "from __main__ import mergeSort", number = 1))
timeReverse.append(timeit("mergeSort({})".format(arrayReverse),
setup = "from __main__ import mergeSort", number = 1))
desenhaGrafico()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment