title: Why does this "improvement" to this algoirthm not work?
body: <p>I created an algorithm to solve the following problem statement: 
  The problem statement is :</p>
  
  <p>We say that two integers x and y have a variation of at least K, if |x − y| ≥ K (the absolute value of their difference is at least K). Given a sequence of N integers a1,a2,...,aN and K, the total variation count is the number of pairs of elements in the sequence with variation at least K, i.e. it is the size of the set of pairs</p>
  
  <pre><code>{(i,j)|1≤i&lt;j≤N and|ai−aj|≥K}
  </code></pre>
  
  <p>code:</p>
  
  <pre><code>int n, k, count = 0;
  cin &gt;&gt; n &gt;&gt; k;
  
  int v[n];
  
  for (int i = 0; i &lt; n; i++) {
      cin &gt;&gt; v[i];
  }
  
  sort(v, v + n);
  
  for (int i = 0, j = 1; i &lt; n;) {
  
      if (abs(v[i] - v[j]) &gt;= k) {
          count += (n-j);
          i++;
      }
      else
          j++;
  }
  cout &lt;&lt; count;
  return 0; }
  </code></pre>
  
  <p>If we have the input:</p>
  
  <pre><code>4 1 // first int is the number of N integers, the second int is the k.
  3 1 3 2 // first integers.
  </code></pre>
  
  <p>So my problem is the following: If I want to improve the algorithm by adding j++ under the i++ in the if block, the output changes from 5 (the correct one) to 4. When i test this improvement on papper and it seems to work, but in code it doesn't, why?</p>