2014-03-06 124 views
1

我瞭解大部分代碼但是我只是困惑兩條線冒泡排序 - 困惑2線(初級)

position = position + 1 
N = N - 1 

他們是怎麼在做代碼和爲什麼他們在結束了嗎?還有什麼其他的方式來寫這兩行?有沒有更有效的方式來編寫這段代碼?

data = [8,7,12,4,9,6,5] 
N = len(data) 
swapped = True 
while swapped: 
    swapped = False 
    position = 0 

    while (position < N - 1): 
     if (data[position] > data[position + 1]): 
      hold = data[position] 
      data[position] = data[position + 1] 
      data[position + 1] = hold 
     else: 
      swapped = True 
     position = position + 1 
    N = N - 1 

print(data) 
+0

氣味就像一個作業問題 –

+0

如果你正在尋找一種有效的方法,你根本不應該考慮冒泡排序。 –

回答

0
len(data)=7 // length of array 
position=0 //to set at beginning of the array 

while(position<N-1) // scans your entire array till end of the array 

if(data[position]>data[position+1]) // checks if 8 >7 if true store 8 in temp variable 
then loop through to get smallest number at data[position] and 
else 
N=N-1 //get next value of N to meet the condition data[position]>data[position+1] 

// prints(sorted array) 

在等價的C代碼:

for(int x=0; x<n; x++) 
     { 
      for(int y=0; y<n-1; y++) 
      { 
       if(array[y]>array[y+1]) 
       { 
        int temp = array[y+1]; 
        array[y+1] = array[y]; 
        array[y] = temp; 

        } 
      } 
     } 

Notice that this will always loop n times from 0 to n, so the order of this algorithm is O(n^2). This is both the best and worst case scenario because the code contains no way of determining if the array is already in order.

嗯 「我認爲冒泡排序將是一個錯誤的路要走。」 :)