2. Now that you have implementations of Bubble Sort and Insertion Sort, please d
ID: 3739390 • Letter: 2
Question
2. Now that you have implementations of Bubble Sort and Insertion Sort, please do the following and report your results. (a) (10 points - Code in m-file, results) Use 'tic Iad 'toe' to time the Insertion Sort algorithm sorting a random vector with 500, and 1000 entries (Do this five times and report the average time) using a script similar to this: seript to test sorting speed. v-rand (1, 1000) tici V-DS.InsertionSort (V) toc (10 points- Code in m-file, results) Use 'tic' and 'toc' to time your Insertion Sort algorithm sorting a random vector with 500, and 1000 entries (Do this five times and report the average time) using a script similar to this: (b) Script to test sorting speed v-rand (3,1000) tic v-bs.subbleSort (V)Explanation / Answer
2)Problem
a) Insertion Sort average time
ScreenShot:-
Code:-
%random vector
v=rand(1,1000);%instead of 1000 put 500 for 500 sorting
%variable for elapsed time total
t=0;
%insertion sort function
function v=InsertionSort(v)
n = length(v);
for j = 2:n
pivot = v(j);
i = j;
while ((i > 1) && (v(i - 1) > pivot))
v(i) = v(i - 1);
i = i - 1;
end
v(i) = pivot;
end
end
%elapsed time calculatio using tic toc timer
tic;
%loop to execute 5 times
for i=1:5
%call insertion sort
v=InsertionSort(v);
%calculate total time
t+=toc;
end
%display average time needed
avgTime1000=t/5
----------------------------------------------------------------------------------------------------------------------------
b) Bubble sort Average time
ScreeShot
Code
%random vector
v=rand(1,1000);%instead of 1000 put 500 for 500 sorting
%variable for elapsed time total
t=0;
%Bubblesort sort function
function v=BubbleSort(v)
n = length(v);
while (n > 0)
% Iterate through x
newVal = 0;
for i = 2:n
% Swap elements in wrong order
if (v(i) < v(i - 1))
v = swap(v,i,i - 1);
newVal = i;
end
end
n = newVal;
end
end
%swap values to make order
function v = swap(v,i,j)
val = v(i);
v(i) = v(j);
v(j) = val;
end
%elapsed time calculation using tic toc timer
tic;
%loop to execute 5 times
for i=1:5
%call insertion sort
v=BubbleSort(v);
%calculate total time
t+=toc;
end
%display average time needed
avgTime1000=t/5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.