Next Permutation In Place

Find the rightmost ascent, swap with the last larger element, reverse the suffix, and reverse everything when the sequence is already maximal.

RustData Integrity

Code

rustsnippet
35 lines
// 原地 (in place) 求下一个排列:找不到升序位说明已是最大排列,
// 整体反转回到最小排列并返回 false
fn next_permutation(items: &mut [i32]) -> bool {
    let n = items.len();
    let mut pivot = None;
    for i in (0..n.saturating_sub(1)).rev() {
        if items[i] < items[i + 1] {
            pivot = Some(i);
            break;
        }
    }
    let Some(pivot) = pivot else {
        items.reverse();
        return false;
    };
    let mut successor = pivot + 1;
    for j in pivot + 1..n {
        if items[j] > items[pivot] {
            successor = j;
        }
    }
    items.swap(pivot, successor);
    items[pivot + 1..].reverse();
    true
}

fn main() {
    let mut items = vec![1, 2, 3];
    loop {
        println!("{items:?}");
        if !next_permutation(&mut items) {
            break;
        }
    }
}

How the snippet works

Next Permutation In Place is built around the functions next_permutation and main.

A single loop drives the file — for i in (0..n.saturating_sub(1)).rev().

Watch out for

  • Its one and only prerequisite is the language toolchain.

Using it

Signature: fn next_permutation(items: &mut [i32]) -> bool

Execute the file and main walks through next_permutation, in that order.

Key statements

let Some(pivot) = pivot else {
    items.reverse();
    return false;
};
let mut pivot = None;
pivot = Some(i);

Interactive Tools for This Topic

FAQ

How do you run Next Permutation In Place?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.