【问题标题】:postfix and prefix in for loopfor循环中的后缀和前缀
【发布时间】:2014-05-15 06:14:19
【问题描述】:

我遇到了这些用于排序的示例,我对这里的后缀和前缀感到很困惑——为什么它使用最后一个——但这里是 ++currIndex?在第二个例子中,它只使用了 ++pass 和 ++index?这些在排序中重要吗?非常感谢!

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

【问题讨论】:

标签: java for-loop increment


【解决方案1】:

对于您的特定示例 ++variable_name 和 variable_name++ 没有太大区别。 在第一个例子中, 它们从初始索引开始,这就是使用 ++currIndex 的原因。 在 for 循环中的相同示例中,它们从最后一个索引开始并到达第一个索引,它们使用了 last--(或 --last 在这里)。

在第二个例子中,对于两个 for 循环,它们都是从第一个索引开始的,这就是使用 ++pass 和 ++index 的原因。

【讨论】:

    【解决方案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 执行的操作,然后再递增

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多