2016-09-13 35 views
-2

我是一名初學者程序員,我一直試圖在Python中創建自己的排序算法,我不明白爲什麼它只輸出輸入中存在的一些數字。我把調試打印放在任何地方去了解問題,但仍然沒有任何東西。代碼應該找到最後一個數組,並將其移至最大數組,輸入數組的最大數量,直到輸入數組爲空,但似乎停止在某個點。有一個人有similar problem,但該解決方案也不適用於我。這是代碼:(並有在輸入的兩個5S)我的排序算法有什麼問題?

array = [3, 6, 25, 4, 5, 24, 7, 15, 5, 2, 0, 8, 1] #just random numbers 
output = [] 
while(len(array) > 0): 
    maximum = 0 
    for x in array: 
     maximum = max(maximum, x) 
    output.append(maximum) 
    tempArray = [] 
    for x in array: 
     temp = array.pop() 
     if(temp < maximum): 
      tempArray.append(temp) 
    array = tempArray 
print(output) 
+0

您可以發佈您的確切輸出嗎? – LaneL

+1

調試提示:從較小的測試用例開始,這樣可以更容易地確定您對程序工作方式的假設是否正確。 ]',例如。 – molbdnilo

+0

@LaneL輸出結果是:[25,15,7,5] – Hexwell

回答

4

的問題是在這裏:

for x in array: 
    temp = array.pop() 

你修改你遍歷同一個列表。這會造成麻煩。

+0

這導致了這個問題..爲什麼要使用temp?你不是mod如果有x,爲什麼不直接追加它? –

0

考慮當5是最大個究竟一個5被添加到輸出,5S的其餘永遠不會加入到tempArray。

+0

我會解決這個問題,謝謝 – Hexwell

0

要進行診斷,請在循環中放置一些調試打印,如外循環末尾的print(output, array)。在內部循環中也許更多。看到的問題(從陣列中除去兩個東西每個內部迭代之後,這個工程。

array = [3, 6, 25, 4, 5, 24, 7, 15, 5, 2, 0, 8, 1] #just random numbers 
output = [] 
while(array): 
    maximum = 0 
    for x in array: 
     maximum = max(maximum, x) 
    output.append(maximum) 
    tempArray = [] 
    for x in array: 
     if(x < maximum): 
      tempArray.append(x) 
    array = tempArray 
print(output) 

有,當然,更方便,更好的方式來刪除陣列最大,而只能刪除最大的一個副本,而不是所有