Implementation and Runtime Analysis of Merge Sort VS Insertion Sort Algorithm
Implementation and Runtime Analysis of Merge Sort VS Insertion Sort Algorithm
Methodology:
"""
"""
import numpy as np
import time
import matplotlib
plt.close('all')
def InsertionSort(A):
for y in range(1,len(A)):
key=A[y]
x=y-1
x-=1
A[x+1]=key
def MergeSort(B):
if len(B)>1:
mid=len(B)//2
left=B[:mid]
right=B[mid:]
MergeSort(left)
MergeSort(right)
x=y=z=0
B[z]=left[x]
x=x+1
else:
B[z]=right[y]
y=y+1
z=z+1
while x<len(left):
B[z]=left[x]
x=x+1
z=z+1
while y<len(right):
B[z]=right[y]
y=y+1
z=z+1
steps=100
time_count=np.zeros(steps)
for x in range(steps):
start_time=time.process_time()
A_size=20*x
A=np.random.randint(low=100,high=1000,size=A_size)
InsertionSort(A)
time_count[x]=time.process_time()-start_time
plt.plot(time_count)
time_count=np.zeros(steps)
for x in range(steps):
start_time=time.process_time()
A_size=20*x
A=np.random.randint(low=100,high=1000,size=A_size)
MergeSort(A)
time_count[x]=time.process_time()-start_time
plt.plot(time_count)
Conclusion: Insertion sort does not perform so well compared to merge sort.Insertion sort exhibits a good
performance when dealing with a small list. It does take a lot of time with big list.Whereas merge sort works
perfectly fine with big list.We can say merge sort is more efficient than insertion sort.
Reference:
[1] https://www.hackerearth.com/practice/algorithms/sorting/merge-sort/tutorial/
[2] https://en.wikipedia.org/wiki/Merge_sort
[3] https://www.tutorialspoint.com/data_structures_algorithms/merge_sort_algorithm.htm