2013-10-02 24 views
0

我寫一個實現了插入排序算法進行排序數組的程序:如何:用double comparisson將while循環拆分爲兩個?

public void insertionSort() 
{ 
    int in, out; 

    for (out = 1; out < nElems; out++)  // out is dividing line 
    { 
     copies++;      
     long temp = a[out];   // remove marked item 
     in = out;      // start shifts at out 
     while (in > 0 && a[in - 1] >= temp) // until one is smaller, 
     { 
      a[in] = a[in - 1];   // shift item to right 
      --in;      // go left one position 
      ++comparissons;    
     } 
     a[in] = temp;     // insert marked item 
    } // end for 
} // end insertionSort(

我也執行該算多少比較算法的過程中,由計數器。在我while循環:

while (in > 0 && a[in - 1] >= temp) // until one is smaller, 
    { 
     a[in] = a[in - 1];   // shift item to right 
     --in;      // go left one position 
     ++comparissons;    
    } 

兩個比較製成,這意味着對於這兩個比較「comparissons」變量只加一(即使兩個比較實際製造)。

我的問題是:我如何分解這個while循環,將兩個比較分成兩部分,這樣每次實際進行比較時都可以增加'comparissons',同時保留相同的功能。

謝謝!

JLL

回答

1

您是否指的是while條件中的比較?如果是,請分別檢查這些條件

while (in > 0) // until one is smaller, 
{ 
    ++comparissons; 
    if (a[in - 1] >= temp) ++comparissons; 
    else      break; 

    a[in] = a[in - 1];   // shift item to right 
    --in;      // go left one position   
} 
+0

太棒了,謝謝!該代碼的作品,但我仍然試圖圍繞邏輯我的頭。 –

+0

@ J.L.Louis在if條件中移動while循環內的條件2來計算它所做的比較2。計算條件1的比較1(原始)。你也想確保當條件2不滿足時循環中斷 – hrv

1

將比較結果移到if循環中。

while (in > 0) { 
    // Move the comparison increment here. 
    if (a[in -1] >= temp) { 
     // The rest of the original while code here. 
    } else { 
     break; 
    } 
} 

或者你可以做這樣的破解並將比較增量移動到條件本身。

while (in > 0 && ((a[in-1] >= temp) && (++comparisons > -1))) { 
} 
+0

問題仍然存在;每次while循環檢查條件時,進行兩次比較(在> 0?...是[in-1]> = temp?),但比較變量只增加1.我需要'比較'每次進行單個比較時都會增加,所以我認爲這必須分成兩個部分,我可以實現++比較。謝謝! :) –