 <p>Please change the looping condition in your for 1st loop !</p> <pre><code>i &lt;= len </code></pre> <p>to </p> <pre><code>i &lt; len </code></pre> <p>It goes from 0 ... n-1 </p> <p>Also you need to change initialization condition in 2nd loop</p> <pre><code>int j = len </code></pre> <p>to</p> <pre><code>int j = len-1 </code></pre> <p>It goes from n-1 ... 0</p>