Info

此问题已关闭。 请重新打开它进行编辑或回答。

You will be estimating the number of swaps required for a list that is X=100, 200, 300, ..., 900, and 1000 numbers long. In other words, you will calculate an average for each number from 100 to 1000 in steps of 100. Each average should be calculat

1 次查看(过去 30 天)
x=[];
numsteps=0;
for N=[100]
for i=1:N
x=[x,floor(999*rand(1)+1)];
end
for i=1:N-1
for j=1:N-i
if (x(j)>x(j+1))
temp=x(j);
x(j)=x(j+1);
x(j+1)=temp;
numsteps= numsteps + 1;
end
end
end
end
fprintf('the number of steps is %d\n', numsteps);
This is my code. I need it to loop again for different values of n like 200, 300, 400...1000. also need it to display the number of steps for each n. I just cant figure out how to have it loop back with a different number of n. Please help?

回答(1 个)

Rik
Rik 2020-1-24
You probably want to use randperm to generate the random list. If you don't want to, you should preallocate the x vector and fill it using indexing.
The source of your problem is that you aren't treating this like a function. Try to rewrite this so you can put in a value for N at the beginning and get numsteps out at the end. Once you have done that, it is easy to put the entire thing in a for loop like this:
for N=100:100:1000
%your updated code
fprintf('For N=%d, the number of steps is %d\n',N,numsteps);
end
Since this is homework I'm not going to give you a copy-paste solution, but feel free to ask for additional hints and/or clarification.
  3 个评论
Rik
Rik 2020-1-24
This is what happens with only a few minor edits to your code:
N=100;
numsteps=0;
x=zeros(N,1);
for ind1=1:N
x(ind1)=floor(999*rand(1)+1);
end
for ind1=1:N-1
for ind2=1:N-ind1
if (x(ind2)>x(ind2+1))
temp=x(ind2);
x(ind2)=x(ind2+1);
x(ind2+1)=temp;
numsteps= numsteps + 1;
end
end
end
fprintf('the number of steps is %d\n', numsteps);
Now you have no warning left from m-lint, and you are most of the way to a solution to your homework.
The assignment wants you to find the average number of steps, which you haven't done yet. This code only finds the number of steps for one particular random vector. Also, the answer is not for N=1000, but for N=100.
Since you essentially have a function here, you only need to find the average number of steps for a given N, and to repeat that process for different values of N.

此问题已关闭。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by