简体   繁体   中英

postfix and prefix in for loop

I came across these examples for sorting, and I'm rather confused about the postfix and prefix here- why it used last-- but ++currIndex here? and in the second example it only used ++pass and ++index? Does these matter in sorting? Many thanks!

for (int last = n-1; last >= 1; last--) {
    int largest = indexOfLargest(theArray, last+1);
     int temp = theArray[largest]; 
     swap theArray[largest] = theArray[last]; 
     theArray[last] = temp;
 }

 private static int indexOfLargest(int[] theArray, int size) { 
     int indexSoFar = 0;
     for (int currIndex = 1; currIndex < size; ++currIndex) {
        if (theArray[currIndex]>theArray[indexSoFar])
           indexSoFar = currIndex;
      }
  return indexSoFar;

Example 2:

for (int pass = 1; (pass < n) && !sorted; ++pass) {
     sorted = true; 
       for (int index = 0; index < n-pass; ++index) {
           int nextIndex = index + 1;
           if (theArray[index]>theArray[nextIndex]) {
               int temp = theArray[index];
               theArray[index] = theArray[nextIndex];
               theArray[nextIndex] = temp;
 }

In simple, it doesn't affect sorting. It's your logical decision on how you wanted to perform the incrementation/decremental

For example

int i = 0;

while (something) {  //any loop for/while
    array[++i] = some data; //increment i first and then next do operation
}

is similar to 

int i = 1;
while (something) {
    array[i++] = some data; //do operation and then increment
}

But the important difference is ++i is executed first and then the operation you wanted to perform based on i. In the other case, it's operation performed on i first and then incrementation

For your particular example ++variable_name and variable_name++ does not make much difference. In first example, they are starting from initial index and that's why used ++currIndex. In same example in for loop they are starting from last index and to reach first index they have used last-- (or --last in here).

and in second example for both for loops they are starting from first index and that's why using ++pass and ++index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM