Java Integer Array Permutation nextPermutation(int[] next)

Here you can find the source of nextPermutation(int[] next)

Description

next Permutation

License

Open Source License

Declaration

public static int[] nextPermutation(int[] next) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static int[] nextPermutation(int[] next) {
        // the counts can swap among each other. The int[] is originally in ascending order
        // this generates the next array in lexicographic order descending

        // locate the last occurrence where next[k] < next[k+1]
        int gt = -1;
        for (int idx = 0; idx < next.length - 1; idx++) {
            if (next[idx] < next[idx + 1]) {
                gt = idx;//from  w  w  w  . j  a v a  2 s  .c om
            }
        }

        if (gt == -1) {
            return null;
        }

        int largestLessThan = gt + 1;
        for (int idx = 1 + largestLessThan; idx < next.length; idx++) {
            if (next[gt] < next[idx]) {
                largestLessThan = idx;
            }
        }

        int val = next[gt];
        next[gt] = next[largestLessThan];
        next[largestLessThan] = val;

        // reverse the tail of the array
        int[] newTail = new int[next.length - gt - 1];
        int ctr = 0;
        for (int idx = next.length - 1; idx > gt; idx--) {
            newTail[ctr++] = next[idx];
        }

        for (int idx = 0; idx < newTail.length; idx++) {
            next[gt + idx + 1] = newTail[idx];
        }

        return next;
    }
}

Related

  1. nextPermutation(int v)
  2. nextPermutation(int[] arr)
  3. nextPermutation(int[] is)
  4. nextPermutation(int[] nums)