Next Permutation Algorithm Visualizer

An interactive tool to understand the next permutation algorithm step-by-step.

Visualization

Enter an array and click 'Visualize' to begin.

Comparing
Pivot
Swap With
Swapping
Reversing

Algorithm Code


1  public void nextPermutation(int[] n) {
2      int ind = -1;
3      // 1. Find the first decreasing element from the right
4      for(int i = n.length - 2; i >= 0; i--) {
5          if(n[i+1] > n[i]) {
6              ind = i;
7              break;
8          }
9      }
10     // 2. If no such element, reverse the whole array
11     if (ind == -1) {
12         reverse(n, 0, n.length - 1);
13         return;
14     }
15 
16     // 3. Find element just larger than n[ind] from the right
17     for(int i = n.length - 1; i > ind; i--) {
18         if(n[i] > n[ind]) {
19             swap(n, i, ind);
20             break;
21         }
22     }
23     // 4. Reverse the part of array after ind
24     reverse(n, ind + 1, n.length - 1);
25 }