2016-06-11 17 views
-2

晚上好。我已經設法冒泡排序listOne。 ListTwo也需要排序。有沒有辦法將listTwo添加到我已經擁有的冒泡排序中,以便它也被排序。 或者我需要寫另一個循環?單一功能冒泡排序2列表

listOne = [3, 9, 2, 6, 1] 
    listTwo = [4, 8, 5, 7, 0] 

    def bubbleSort (inList): 

    moreSwaps = True 
while (moreSwaps): 
    moreSwaps = False 
    for element in range(len(listOne)-1): 
     if listOne[element]> listOne[element+1]: 
      moreSwaps = True 
      temp = listOne[element] 
      listOne[element]=listOne[element+1] 
      listOne[element+1]= temp 
return (inList) 

     print ("List One = ", listOne) 
     print ("List One Sorted = ", bubbleSort (listOne)) 
     print ("List Two = ", listTwo) 
     print ("List Two Sorted = ", bubbleSort (listTwo)) 
+0

你聽說有關被叫範式 '方法' ?如果不是,你可以在這裏閱讀:[方法](https://en.wikipedia.org/wiki/Method_(computer_programming)) 而對於python:[Python是什麼「方法」?]( http://stackoverflow.com/q/3786881/4907452) –

回答

1

我想你只需要一個方法,然後調用稱它爲兩個列表上,你可以試試這個: 這是一個方法來爲你做兩份工作。

listOne = [3, 9, 2, 6, 1] 
listTwo = [4, 8, 5, 7, 0] 

def bubblesort(array): 
    for i in range(len(array)): 
     for j in range(len(array) - 1): 
      if array[j] > array[j + 1]: 
       swap = array[j] 
       array[j] = array[j + 1] 
       array[j + 1] = swap 
    print(array) 


bubblesort(listOne) 
bubblesort(listTwo) 

[1,2,3,6,9]

[0,4,5,7,8]

+0

是的!謝謝。做得好。 ^^ – user662973

+0

@ user662973我很樂意幫助 –

+0

謝謝!剛剛寫了另一個子程序來做第二個列表的冒泡排序。 – user662973