簡體   English   中英

調用內的Java增量/減量運算符

[英]java increment/decrement operator inside call

我們正在學習quickSort。 本書在我的問題結尾處提供了代碼。

我對findPivot方法末尾的調用感到好奇:

swap(array, left++, right--);

為什么在其中有“ ++”和“-”? 它不是在交換之前或之后遞增/遞減變量,也不在訪問(例如)array [left + 1]。

那有什么呢?

編輯

因此,在發布問題之前,我編寫了以下測試代碼:

public static void main(String[] args) {

    int a = 0;
    int b = 2;
    int[] array = {1,10,20,30};

    swap(array, a++,b--);

}

public static void swap(int[]array,int a, int b) 
{
    for(int i = 0; i < 10; i++)
    {
    Integer temp = array[a];
   array[a] = array[b];
   array[b] = temp;

    System.out.println("a = " + a + "\nb = " + b + "\narray a: " + array[a] + "\narray b: " + array[b]);
    }

結果如下:

a = 0 b = 2數組a:20數組b:1 a = 0 b = 2數組a:1數組b:20 a = 0 b = 2數組a:20數組b:1

在該方法中使用時,該變量根本不后遞增。 這就是為什么我問這個問題。

謝謝。 這是代碼:

private static void swap(Integer[] array, int i, int j)
{

   Integer temp = array[i];
   array[i] = array[j];
   array[j] = temp;

}

public static void quickSort(Integer[] array, int left, int right)
{
    if(left < right)
    {
        int pivot = findPivot(array, left, right);
        quickSort(array, left, pivot - 1);
        quickSort(array, pivot + 1, right);
    }
}//quickSort

public static int findPivot(Integer[] array, int left, int right)
{
    int first = left++;
    while (left <= right)
    {
        while (left <= right && array[first].compareTo(array[left]) > 0)
        {
            left++;
        }
        while (left <= right && array[first].compareTo(array[right]) < 0)
        {
            right--;
        }
        if (left < right)
            swap(array, left++, right--);
    }
    swap(array, first, right);
    return right;
}

它是后遞增(§15.14.2)++ )和后遞減(§15.14.3)-- )操作。 這些將更改while循環中下一次迭代的值。

您基本上有這個:

while (left <= right)
{
    // ...
    if (left < right)
    {
        swap(array, left, right);
        left++;
        right--;
    }
}

如您所見,“ post”表示該值不受該特定語句的影響。 在評估后遞增操作后,將增加該變量,但傳遞給該方法的值仍然是舊值。 對於高級讀者,您可以這樣編寫后遞增運算符(偽代碼):

public int operator this++()
{
    int temp = this;
    ++this; // regular pre-increment (JLS §15.15.1)
    return temp;
}

要了解有關預遞增運算符的信息,可以查看JLS§15.15.1

swap(array, left++, right--); while循環內,因此更新的值將在下一個循環迭代中使用。

Java的increment( ++ )和decrement( -- )讓我們假設i++; 這意味着i+1i--表示編程中的i-1

int i = 1;
System.out.println("i : "+(i++)); // this means first print then add `1` into i;
//and
System.out.println("i : "+(++i)); // this means first add one and then print it;
// same for '--' 

它們是后遞增(++)和后遞減(-)操作,因此它們將在while循環的下一次迭代中更改值

在此行的代碼中

   swap(array, left++, right--);//left++ , right-- are post increment (++) and post decrement (--) operation

暫無
暫無

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

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