What's wrong with my bubble code?

14 ビュー (過去 30 日間)
bobsoney bobsoney
bobsoney bobsoney 2018 年 12 月 21 日
コメント済み: Stephen23 2024 年 10 月 30 日
clc
function y = sort( v )
n = length( v );
sorted = 0;
k = 0;
while ~sorted
sorted = 1;
k = k + 1;
for j = 1:n-k
if v(j) > v(j + 1)
t = v(j);
v(j) = v(j + 1);
v(j + 1) = t;
sorted = 0;
end
end
end
y = x;
This code ain't doing [anything] guys. What's wrong? Should I put v = input( 'vector? ' ) before the function or something? What's the point of the y = x;?

採用された回答

per isakson
per isakson 2018 年 12 月 21 日
編集済み: per isakson 2018 年 12 月 21 日
The red markers in the right column indicates that something is seriously wrong
Right click function
(There is already a function named sort in Matlab. Pick another name. )
Remove the first line (and add end as the last line).
Try
function y = my_sort( v )
n = length( v );
sorted = 0;
k = 0;
while ~sorted
sorted = 1;
k = k + 1;
for j = 1:n-k
if v(j) > v(j + 1)
t = v(j);
v(j) = v(j + 1);
v(j + 1) = t;
sorted = 0;
end
end
end
y = x;
end
I get
Cannot find an exact (case-sensitive) match for 'x
The closest match is: X in H:\m\cssm\X.m
Error in my_sort (line 19)
y = x;
Replace
y = x;
by
y = v;
and try again
>> my_sort( randi(12,1,6) )
ans =
2 4 7 12 12 12
>>
  1 件のコメント
Stephen23
Stephen23 2024 年 10 月 30 日
"Replace ... by ... "
Or even simpler: get rid of both of them and just make the output v.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by