Matlab: i=2, if B(i)>B(i+1)... 下标索引错误,必须为正整数
Matlab: i=2, if B(i)>B(i+1)... Subscript index error, must be positive integer
我正在为 class 编写排序算法,第 14 行出现此错误,下标索引必须是实数正整数或逻辑数。我在不同的线程中搜索了答案,但答案似乎令人困惑并且与我的问题无关。我理解错误的含义,但不明白为什么我的代码会失败。 i=2 是一个正整数,没有非整数或负整数的除法或乘法,据我所知,下标索引的位置没有零。我不明白。在此先感谢您的帮助!
function bubblesort(A)
%bubble sorting algo
B=A;
c=numel(B);
%count the number of elements in a, store it as c
if B(1)>B(2)
left=B(1);
right=B(2);
B(1)=right;
B(2)=left;
end
i=2;
while i+1<=c
**if B(i)>B(i+1)**
left=B(i);
right=B(i+1);
B(i)=right;
B(i+1)=left;
i=i-1;
else
i=i+1;
end
end
B
end
问题在于(除非 A 的第一个元素已经是最小的)i = i-1 行将使最小元素的 i = 0 并且代码将失败。我认为如果 i>1.
可以固定添加函数
function bubblesort(A)
%bubble sorting algo
B = A;
c = numel(B);
%count the number of elements in a, store it as c
i = 1;
while i+1 <= c
if B(i) > B(i+1)
left = B(i);
right = B(i+1);
B(i) = right;
B(i+1) = left;
if i > 1
i = i-1;
end
else
i = i+1;
end
end
B
end
我正在为 class 编写排序算法,第 14 行出现此错误,下标索引必须是实数正整数或逻辑数。我在不同的线程中搜索了答案,但答案似乎令人困惑并且与我的问题无关。我理解错误的含义,但不明白为什么我的代码会失败。 i=2 是一个正整数,没有非整数或负整数的除法或乘法,据我所知,下标索引的位置没有零。我不明白。在此先感谢您的帮助!
function bubblesort(A)
%bubble sorting algo
B=A;
c=numel(B);
%count the number of elements in a, store it as c
if B(1)>B(2)
left=B(1);
right=B(2);
B(1)=right;
B(2)=left;
end
i=2;
while i+1<=c
**if B(i)>B(i+1)**
left=B(i);
right=B(i+1);
B(i)=right;
B(i+1)=left;
i=i-1;
else
i=i+1;
end
end
B
end
问题在于(除非 A 的第一个元素已经是最小的)i = i-1 行将使最小元素的 i = 0 并且代码将失败。我认为如果 i>1.
可以固定添加函数function bubblesort(A)
%bubble sorting algo
B = A;
c = numel(B);
%count the number of elements in a, store it as c
i = 1;
while i+1 <= c
if B(i) > B(i+1)
left = B(i);
right = B(i+1);
B(i) = right;
B(i+1) = left;
if i > 1
i = i-1;
end
else
i = i+1;
end
end
B
end