Next permutation
Find the next lexicographic arrangement of the array, in place, without listing every permutation.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Scan from the right for the first index i where the order rises (a[i] < a[i + 1]); everything after i is already the largest possible arrangement of those values. Swap a[i] with the smallest value after it that still beats it, then reverse the falling tail so it becomes the smallest possible arrangement again.
Code
public static void NextPermutation(int[] a) {
int i = a.Length - 2;
while (i >= 0 && a[i] >= a[i + 1]) i--;
if (i >= 0) {
int j = a.Length - 1;
while (a[j] <= a[i]) j--;
(a[i], a[j]) = (a[j], a[i]);
}
Reverse(a, i + 1, a.Length - 1);
}
static void Reverse(int[] a, int l, int r) {
while (l < r) { (a[l], a[r]) = (a[r], a[l]); l++; r--; }
}static void nextPermutation(int[] a) {
int i = a.length - 2;
while (i >= 0 && a[i] >= a[i + 1]) i--;
if (i >= 0) {
int j = a.length - 1;
while (a[j] <= a[i]) j--;
int t = a[i]; a[i] = a[j]; a[j] = t;
}
reverse(a, i + 1, a.length - 1);
}
static void reverse(int[] a, int l, int r) {
while (l < r) { int t = a[l]; a[l] = a[r]; a[r] = t; l++; r--; }
}void reverseRange(vector<int>& a, int l, int r) {
while (l < r) { swap(a[l], a[r]); l++; r--; }
}
void nextPermutation(vector<int>& a) {
int i = (int)a.size() - 2;
while (i >= 0 && a[i] >= a[i + 1]) i--;
if (i >= 0) {
int j = (int)a.size() - 1;
while (a[j] <= a[i]) j--;
swap(a[i], a[j]);
}
reverseRange(a, i + 1, (int)a.size() - 1);
}def next_permutation(a: list[int]) -> None:
i = len(a) - 2
while i >= 0 and a[i] >= a[i + 1]: i -= 1
if i >= 0:
j = len(a) - 1
while a[j] <= a[i]: j -= 1
a[i], a[j] = a[j], a[i]
reverse(a, i + 1, len(a) - 1)
def reverse(a: list[int], l: int, r: int) -> None:
while l < r: a[l], a[r] = a[r], a[l]; l += 1; r -= 1Tips
- If no such i exists, the whole array is falling: it is the last permutation, and the next one wraps around to the smallest, fully reversed, arrangement.
- The same pivot-then-reverse shape also finds the previous permutation, with every comparison flipped.
In the .NET library
Generating and sorting every permutation to find the next one is O(n!); this in-place scan does it in O(n).