2016-08-11 175 views
1

我有下面这个Python代码(用于冒泡排序)。下面是我将它转换为MATLAB代码的尝试。我是MATLAB新手,正在为练习做转换。如果我的转换有多准确/不正确,我将不胜感激。Python到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 
+0

我忘记了Python代码if语句下添加缩进。修正了编辑错误。 –

+2

您是否测试过是否对输入进行排序? – Suever

+0

1)它是否按预期工作? 2)为什么是递归的? –

回答

2

的几个问题:

  1. 您需要使用numel而非size到获取数组中的元素数量。 size会给你每个维度的大小的矢量和numel会给你的元素

  2. 实际上你需要通过你的for循环来创造价值的一个数组的总数。为此,请使用冒号创建一个从2n的数组。

    for ii = 2:n 
    end 
    
  3. 您使用ii作为循环变量,但尝试使用i环路内。选择一个,并坚持下去(最好不要i

  4. 要翻转值,你可以简单地做你的任务是这样的:

    alist([i-1, i]) = alist([i, i-1]); 
    

总之,这会给你这样的事情:

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 
+0

这是非常丰富的,谢谢。 –

1

你的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 
end 
+0

哦,谢谢你提到我的低效率问题。我正在努力学习所有关于排序算法的知识,所以每一点都有所帮助。 –