Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.53 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. from timeit import timeit
  3. from random import randint
  4. import itertools as it
  5.  
  6. #merge is intercalation . sort tow vectors in crescent order,
  7. #intercale and put them in crescent order too
  8.  
  9. # The interleave function consists essentially of moving elements of the vector v from one place to another (first from v to w and then from w to v).
  10. # The function executes 2n of these moves, where n is the size of the vector v [p..r-1].
  11. # The time it consumes is proportional to the number of movements.
  12. # Therefore, the time consumption of the function is proportional to n. Thus, the algorithm is linear.
  13.  
  14. def mergeSort(x):
  15. result = []
  16. # if len(vector is smaller than 2, the vector is arranged)
  17. if len(x) < 2:
  18. return x
  19. # divide your vector in the middle and call recursively the function
  20. #the function is called until all the vector is ordered
  21. mid = int(len(x)/2)
  22. y = mergeSort(x[:mid])
  23. z = mergeSort(x[mid:])
  24. while (len(y) > 0) or (len(z) > 0):
  25. if len(y) > 0 and len(z) > 0:
  26. if y[0] > z[0]:
  27. result.append(z[0])
  28. z.pop(0)
  29. else:
  30. result.append(y[0])
  31. y.pop(0)
  32. elif len(z) > 0:
  33. for i in z:
  34. result.append(i)
  35. z.pop(0)
  36. else:
  37. for i in y:
  38. result.append(i)
  39. y.pop(0)
  40. return result
  41.  
  42. #generate unSorted array with gave lenght
  43. def listGenerator(lenList):
  44. generated = []
  45. for i in range(lenList):
  46. while len(generated) != lenList:
  47. n = randint(1,1*lenList)
  48. if n not in generated: generated.append(n)
  49. return generated
  50.  
  51. def drawGraph(listQt,medium,best,worst,xl = "Elementos", yl = "Tempo"):
  52. fig = plt.figure(figsize=(10, 8))
  53. ax = fig.add_subplot(111)
  54. ax.plot(listQt,medium, label = "Caso Medio")
  55. ax.plot(listQt,best, label = "Melhor Caso")
  56. ax.plot(listQt,worst, label="Pior Caso")
  57. ax.legend(bbox_to_anchor=(1, 1),bbox_transform=plt.gcf().transFigure)
  58. plt.ylabel(yl)
  59. plt.xlabel(xl)
  60. plt.show()
  61. fig.savefig('mergeSort.png')
  62.  
  63. #lenghts to diferent arrays
  64. length = [10000,20000,30000,40000,50000]
  65.  
  66. #array to store the necessary time to sort each array
  67. mediumTimes = []
  68. bestTimes = []
  69. worstTimes = []
  70.  
  71. for i in length:
  72. mediumList = listGenerator(i)
  73. bestList = sorted(mediumList)
  74. worstList = sorted(bestList, reverse=True)
  75.  
  76. mediumTimes.append(timeit("mergeSort({})".format(mediumList),setup="from __main__ import mergeSort",number=1))
  77. bestTimes.append(timeit("mergeSort({})".format(bestList),setup="from __main__ import mergeSort",number=1))
  78. worstTimes.append(timeit("mergeSort({})".format(worstList),setup="from __main__ import mergeSort",number=1))
  79.  
  80. drawGraph(length, mediumTimes, bestTimes, worstTimes)
  81.  
  82. # Verify the worst case
  83. worstCaseExperience = list(it.permutations([1,2,3,4,5,6],6))
  84.  
  85. # permutimes and worstcase will have the same len, so the index is equivalent each other
  86. permuTimes = []
  87. swaps = []
  88.  
  89. for permutation in worstCaseExperience:
  90. listToSort = list(permutation)
  91. permuTimes.append(timeit("mergeSort({})".format(listToSort),setup="from __main__ import mergeSort",number=1))
  92. swaps.append(mergeSort(listToSort))
  93.  
  94. smallerTime = min(permuTimes)
  95. greaterTime = max(permuTimes)
  96.  
  97. smallerTimeIndex = permuTimes.index(smallerTime)
  98. greaterTimeIndex = permuTimes.index(greaterTime)
  99.  
  100. # worst case list
  101. print("May be the worst: {}".format(worstCaseExperience[smallerTimeIndex]))
  102. print("May be the best: {}".format(worstCaseExperience[greaterTimeIndex]))
  103. print(swaps)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement