我有下面這個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
我忘記了Python代碼if語句下添加縮進。修正了編輯錯誤。 –
您是否測試過是否對輸入進行排序? – Suever
1)它是否按預期工作? 2)爲什麼是遞歸的? –