title: Inaccuracy in code which returns the next permutation of an array
body: <p>I was solving a question on leetcode with the description:</p>
  <blockquote>
  <p>The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p>
  </blockquote>
  <p>This is what I came up with in C++:</p>
  <pre><code>    void nextPermutation(vector&lt;int&gt;&amp; nums) {
          
              int index = -1, j = nums.size() - 1;
  
              for (int i = nums.size() - 1; i &gt; 0; i--)
              {
                  if(nums[i - 1] &lt; nums[i])
                  {
                      index = i - 1;
                      break;
                  }
              }
  
              if(index == -1)
              {
                  reverse(nums.begin(), nums.end());
                  return;
              }
  
              for (int i = nums.size() - 1; i &gt;= index + 1; i--)
              {
                  if(nums[i] &gt; nums[index])
                  {
                      j = i;
                  }
                  break;
              }
  
              swap(nums[index], nums[j]);
              reverse(nums.begin() + index + 1, nums.end());
  
          }
  </code></pre>
  <p>Here I traversed the array from left to right and look for an element which is smaller than the element on its right(named it index), and then traversed it again looking for a number just bigger than the number before and swapped them and then reversed the array after index</p>
  <p>This code works for the example cases but fails in a case where:</p>
  <blockquote>
  <p>Input: [2,3,1]</p>
  </blockquote>
  <blockquote>
  <p>MyOutput: [1,2,3]</p>
  </blockquote>
  <blockquote>
  <p>Expected Output: [3,1,2]</p>
  </blockquote>
  <p>I do not understand what I did wrong and everything should be working but its not.</p>