下面有这个python代码(用于冒泡排序)。下面是我把它转换成MATLAB代码的尝试。我刚开始使用MATLAB,我正在为练习做转换。我希望得到关于我的转换是多么准确/不正确的反馈。
python版本:
def bubble_sort(alist):
return bubble_sort_helper(alist, len(alist))
def bubble_sort_helper(alist, n):
if n < 2:
return alist
for i in range(len(alist)-1):
if alist[i] > alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
return bubble_sort_helper(alist, n-1)我尝试了MATLAB转换:
function a = bubble_sort(alist)
a = bubble_sort_helper(alist, size(alist))
end
function b = bubble_sort_helper(alist, n)
if n < 2
b = alist
end
for ii = size(alist)
if alist(1) > alist (ii+1)
temp = alist(ii)
alist(ii) = alist(ii+1)
alist(ii+1) = temp
end
end
b = bubble_sort_helper(alistn n-1)
end发布于 2016-08-11 19:23:14
这里有几个问题:
numel而不是size来获取数组中的元素数。size将给出每个维度的大小向量,numel将给出元素的总数。for循环创建一个值数组。为此,使用冒号创建从2到n的数组。
I= 2:n端ii作为循环变量,但尝试在循环中使用i。选择一个并坚持它(最好不是i)加在一起,这会给你这样的东西:
function a = bubble_sort(alist)
a = bubble_sort_helper(alist, numel(alist))
end
function b = bubble_sort_helper(alist, n)
if n < 2
b = alist;
else
for k = 2:n
if alist(k-1) > alist(k)
alist([k-1, k]) = alist([k, k-1]);
end
end
b = bubble_sort_helper(alist, n-1);
end
end发布于 2016-08-11 19:23:44
您的python版本效率低下:
def bubble_sort(alist):
return bubble_sort_helper(alist, len(alist))
def bubble_sort_helper(alist, n):
if n < 2:
return alist
for i in range(n-1):
if alist[i] > alist[i+1]:
alist[i], alist[i+1] = alist[i+1], alist[i]
return bubble_sort_helper(alist, n-1)你的matlab代码是错误的:
function a = bubble_sort(alist)
a = bubble_sort_helper(alist, size(alist))
end
function b = bubble_sort_helper(alist, n)
if n < 2
b = alist;
else
for i = 2:n
if alist(i-1) > alist(i)
temp = alist(i-1);
alist(i-1) = alist(i);
alist(i) = temp;
end
end
b = bubble_sort_helper(alist, n-1);
end
endhttps://stackoverflow.com/questions/38904366
复制相似问题