有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

for循环中的java后缀和前缀

我遇到了这些排序的例子,我对这里的后缀和前缀很困惑——为什么它最后才使用——但是这里的索引呢?在第二个例子中,它只使用了++传递和++索引?这些在分类中重要吗?非常感谢

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;

例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;
 }

共 (2) 个答案

  1. # 1 楼答案

    对于您的特定示例,++变量名和变量名++没有太大区别。 在第一个例子中, 它们是从初始索引开始的,这就是为什么要使用索引。 在for循环中的同一个例子中,它们从最后一个索引开始,到达它们最后使用的第一个索引(或这里的最后一个)

    在第二个例子中,两个for循环都是从第一个索引开始的,这就是为什么要使用++传递和++索引

  2. # 2 楼答案

    简单地说,它不影响排序。 如何执行递增/递减是你的逻辑决定

    比如

    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
    }
    

    但重要的区别是++i首先执行,然后是基于i执行的操作。在另一种情况下,它是首先对i执行的操作,然后是递增操作