簡體   English   中英

每次在for循環中檢查終止表達式時,遞增int

[英]Increment int each time the termination expression is checked in a for loop

每次for循環檢查終止條件時,是否可以增加某些內容? 我正在嘗試比較一個項目的兩種排序算法,並且我增加了交換次數,但是我也想在每次檢查for循環的終止條件時增加一些。 謝謝!

這是我的代碼:

    for(int i=1; i<array.length; i++) {
        for (int j=i; (j>0) && (array[j]<(array[j-1])); j--) {
            Sort.swap(array, j, j-1);
            swaps++;
        }
    } 

如前所述,我想檢查“(j> 0)&&(array [j] <(array [j-1]))”的評估次數,以便可以將其與其他排序算法進行比較。

我嘗試在循環中添加增量,但是在終止表達式中添加增量時出現錯誤,指出無法將其轉換為bool。

感謝您的任何幫助!

我建議你介紹新班Counter

class Counter {
    private int counter = 0;
    public boolean count(boolean b) {
         counter++;
         return b;
    }
    public int getCount() {
         return count;
    }
}

並像這樣使用它:

Counter c = new Counter();
for(int i=1; i<array.length; i++) {
    for (int j=i; c.count((j>0) && (array[j]<(array[j-1]))); j--) {
        Sort.swap(array, j, j-1);
        swaps++;
    }
}
System.out.println(c.getCount()); 

for表達式的最后一個子句在每次迭代時都會求值。 您可以在該空間中放置多個變量增量。

for(int i=1; i<array.length; i++) {
    int checks = 1; // There is always one more check than iterations, the last check being the one which ends the iteration
    for (int j=i; (j>0) && (array[j]<(array[j-1])); j--, checks++) {
        Sort.swap(array, j, j-1);
        swaps++;
    }
    System.out.println(checks);
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM