Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is a MATLAB question. Use function random0 to generate a set of 100,000 ran

ID: 3697019 • Letter: T

Question

This is a MATLAB question.

Use function random0 to generate a set of 100,000 random values. Sort this data set twice, once with the ssort function of Example 6.2, and once with MATLAB's built-in sort function. Use tic and toc to time the two sort functions. How do the sort time compare? Be sure use the same input data.

Here is the ssort code:

function out = ssort(a)
nvals = length(a);

for ii = 1:nvals-1
iptr = ii;
for jj = ii+1:nvals
if a(jj) < a(iptr)
iptr = jj;
end
end
if ii ~= iptr
temp = a(ii);
a(ii)= a(iptr);
a(iptr) = temp;
end
end

out = a;


nvals = input('Enter number of values to sort: ');
array = zeros(1,nvals);

for ii = 1:nvals
string = ['Enter value ' int2str(ii) ': '];
array(ii) = input(string);
end

sorted = ssort(array);
fprintf(' Storted data: ');
  
for ii = 1:nvals
fprintf(' %1.1f ',sorted(ii));
end

Explanation / Answer

%demo.m

nvals = 1000;
array = randi(nvals);
A=zeros(1,nvals+1);
for i=1:nvals
A=array(i);
end
tic;
%calling ssort
sorted = ssort(array);
t1=toc;
tic;
%default sort method
B=sort(A);
t2=toc;
if(t1>t2)
disp("ssort takes more time than defalut sort");
else
disp("Default sort takes more time than ssort");
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%ssort function: ssort.m
function out = ssort(a)
nvals = length(a);
for ii = 1:nvals-1
iptr = ii;
for jj = ii+1:nvals
if a(jj) < a(iptr)
iptr = jj;
end
end
if ii ~= iptr
temp = a(ii);
a(ii)= a(iptr);
a(iptr) = temp;
end
end
out = a;

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote