Advertisement
makispaiktis

InsertionSort vs MergeSort Time

Apr 28th, 2020 (edited)
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. '''
  2. CHAPTER 1
  3. '''
  4.  
  5. def insertionSort(A):
  6.     n = len(A)
  7.     for j in range(1, n):
  8.         key = A[j]
  9.         i = j - 1
  10.         while i >= 0 and A[i] > key:
  11.             A[i + 1] = A[i]
  12.             i = i - 1
  13.         A[i + 1] = key
  14.     return A
  15.  
  16. def Merge(A, p, q, r):
  17.     n1 = q - p
  18.     n2 = r - q + 1
  19.  
  20.     L = []
  21.     R = []
  22.     for i in range(0, n1):
  23.         L.append(A[p + i])
  24.     for j in range(0, n2):
  25.         R.append(A[q + j])
  26.     L.append(float("inf"))
  27.     R.append(float("inf"))
  28.  
  29.     i = 0
  30.     j = 0
  31.     for k in range(p, r + 1):
  32.         if L[i] <= R[j]:
  33.             A[k] = L[i]
  34.             i = i + 1
  35.         else:
  36.             A[k] = R[j]
  37.             j = j + 1
  38.  
  39.  
  40. def mergeSort(A, p, r):
  41.     if p < r:
  42.         q = (p + r) // 2
  43.         mergeSort(A, p, q)
  44.         mergeSort(A, q + 1, r)
  45.         Merge(A, p, q + 1, r)
  46.  
  47.  
  48. import random
  49. B = [random.randint(1, 200) for r in range(200)]
  50.  
  51. '''
  52. CHAPTER 2
  53. '''
  54.  
  55. from timeit import default_timer as timer
  56. executions = list(range(20, 220, 20))
  57. # executions = [20, 40, 60, .... , 180, 200]
  58.  
  59. measurements_insertionsort = []
  60. measurements_mergesort = []
  61. for s in executions:
  62.     start = timer()
  63.     insertionSort(B[0:s])
  64.     end = timer()
  65.     measurements_insertionsort.append(end - start)
  66.     start = timer()
  67.     mergeSort(B[0:s], 0, len(B[0:s]) - 1)
  68.     end = timer()
  69.     measurements_mergesort.append(end - start)
  70.  
  71. print("NumOfElements   InsertionSortTime(ms)      MergeSortTime(ms)")
  72. for e, m1, m2 in zip(executions, measurements_insertionsort, measurements_mergesort):
  73.     print(str(e) + "              " + str(1000 * m1) + "        " + str(1000 * m2))
  74.  
  75.  
  76. '''
  77. CHAPTER 3
  78. '''
  79.  
  80. import matplotlib.pyplot as plt
  81. plt.plot(executions, measurements_insertionsort, label="Insertion Sort")
  82. plt.plot(executions, measurements_mergesort, label="Merge Sort")
  83. plt.xlabel("Number of Elements")
  84. plt.ylabel("Execution Time")
  85. plt.legend()
  86. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement